当前位置:网站首页>Have you learned the necessary global exception handler for the project
Have you learned the necessary global exception handler for the project
2022-07-01 10:01:00 【Previous year 1206】
Preface
Must be in the usual time to write the project , There must have been abnormal situations , Such as null pointer 、 Data transboundary 、 Type conversion . Every time we have to deal with this exception by ourselves , But there may be many places to deal with in a project , We can't deal with it every time , It's a lot of trouble , At this time, I must think of extracting the exception handling . Unified treatment , So our global exception handling appears .
Two things are important —— The idea of exception handling 、 The global exception is Put exception handling into a class for unified processing .
dried food
As mentioned above, the global exception is a class used to handle exceptions uniformly , So we only need a global exception handling class
package com.xinian.springclud_demo.exception;
import com.xinian.springclud_demo.common.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.sql.ResultSet;
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(value = BusinessException.class)
public Result zdyExceptionHandeler (BusinessException e){
System.out.println(" Global exception 1");
log.error(e.getErrorMeg(),e);
return Result.builder().data(e).build();
}
@ExceptionHandler(Exception.class)
public Result exceptionHandler(Exception e){
System.out.println(" Global exception 2");
log.error(e.getMessage(),e);
return Result.builder().data(e).build();
}
}
Be careful
- @RestControllerAdvice Yes controller enhanced , Able to intercept all SpringMVC The abnormal situation produced
- ExceptionHandler The following parameters specify which method the exception enters for processing
The following is the code for writing exceptions , Not the content of the global exception code
package com.xinian.springclud_demo.controller;
import com.xinian.springclud_demo.common.Result;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test")
public class TestException {
@GetMapping("/a")
public Result query(){
int i=1/0;
Result result = new Result(true," good ",200,"hh");
return result;
}
}
Running results 
This is the interception !
This is the end of the global exception interceptor , The following is based on this thing . How to integrate into the project . Construct the basic framework of a project .
- All items must be return values , First, construct the return value type of an item !
package com.xinian.springclud_demo.common;
import com.xinian.springclud_demo.enums.StatusEnum;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Result {
/** * The success of */
private Boolean success;
/** * Return message */
private String message;
/** * Return code */
private Integer code;
/** * Return the data */
private Object data;
/** * success * * @return */
public static Result success() {
return success(null);
}
/** * success * @param data * @return */
public static Result success(Object data) {
Result rb = new Result();
rb.setCode(StatusEnum.SUCCESS.getErrorCode());
rb.setMessage(StatusEnum.SUCCESS.getErrorMsg());
rb.setData(data);
return rb;
}
/** * Failure */
public static Result error() {
Result rb = new Result();
rb.setCode(StatusEnum.FAIL.getErrorCode());
rb.setMessage(StatusEnum.FAIL.getErrorMsg());
rb.setData(null);
return rb;
}
/** * Failure */
public static Result error( String message) {
Result rb = new Result();
rb.setCode(-1);
rb.setMessage(message);
rb.setData(null);
return rb;
}
}
The return value type is well defined , But there are many situations for the status we return , So we finally define an enumeration to list all the States , I use two here
package com.xinian.springclud_demo.enums;
import lombok.Data;
public enum StatusEnum {
SUCCESS (200," success "),
NO_PERMISSION(403, " You don't have access to "),
NO_Auth(401, " unauthorized , Please login for verification "),
NO_FOUND(404, " No resources found "),
INTERNAL_SERVER_ERROR(500, " Server exception , Please contact the Administrator !"),
FAIL(502," Failure ");
private Integer errorCode;
private String errorMsg;
StatusEnum(Integer errorCode,String errorMsg){
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
public Integer getErrorCode() {
return errorCode;
}
public String getErrorMsg() {
return errorMsg;
}
}
If the official abnormal conditions cannot meet your requirements You can also customize exceptions .
You only need to inherit one RuntimeException That's all right. .
package com.xinian.springclud_demo.exception;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class BusinessException extends RuntimeException{
/** * Error code */
protected Integer errorCode;
/** * Error message */
protected String errorMeg;
}
Running results 
This is called global exception handling . Isn't it easy , Just need a class , That's what's called extract
Detailed code please check springboot Global exception handling
边栏推荐
- 【无标题】
- Import and export of power platform platform sharepointlist
- 年薪100万,在北上广深买的起房子吗?
- Introduction to expressions and operators in C language
- Mikrotik Routeros Internet access settings
- SQL learning notes (01) - basic knowledge of database
- Concept of digital currency
- Tearful eyes, it's not easy to change jobs. Three rounds of interviews, four hours of soul torture
- 苹果放大招!这件事干的太漂亮了……
- About widthstep of images in opencv
猜你喜欢

LVGL V8.2字符串显示在Keil MDK上需要注意的事项(以小熊派为例)

那个程序员,被打了。

持续进阶,软通动力稳步推动云智能战略

SQL learning notes (01) - basic knowledge of database

Continue to advance, and softcom power steadily promotes cloud intelligence strategy

Introduction to expressions and operators in C language

架构实战营 模块九:设计电商秒杀系统

The market is relatively weak recently

Concept of digital currency

C one line code calculates the MD5 value of the file - codeplus series
随机推荐
PHP array functions (merge, split, append, find, delete, etc.)
我喜欢两个男人。。。
日本教授起诉英特尔FPGA与SoC产品侵犯一项设计专利
Apple amplification! It's done so well
Fried money, lost 10million.
硬件中台项目
7-Zip boycotted? The callers have committed "three crimes": pseudo open source, unsafe, and the author is from Russia!
遇到女司机业余开滴滴,日入500!
SQL learning notes (04) - data update and query operations
SQL learning notes (02) - database table operation
Graduation summary of actual combat camp
电脑USB、HDMI、DP各种接口及速度
Computer USB, HDMI, DP various interfaces and speeds
Initial experience of Flink, a mainstream real-time stream processing computing framework
UE small knowledge point controller possess pawn process
[fxcg] large scale job hopping may be one of the driving forces behind the soaring inflation in the United States
Introduction of uniapp wechat applet components on demand
亿学学堂帮个人开的证券账户安全吗?是不是有套路
谁还在买“三只松鼠”们
Wechat emoticons are written into the judgment, and the OK and bomb you send may become "testimony in court"