springboot + @ControllerAdvice + @ExceptionHandler 实现全局异常拦截,不用

2021-01-18 01:15

阅读:792

标签:size   不用   tco   使用   异常   实体   创建   hand   success   

1.目的:实现全局异常拦截,不用在controller在写try catch,使用代码看起来更加整洁

 

2.不啰嗦直接上代码

2.1首先我们创建一个异常捕获处理类(@RestControllerAdvice = @ControllerAdvice + @ResponseBody)

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

/**
* 处理 Exception 异常
*
* @parame
* @param e 异常
* @return
*/
@ExceptionHandler(value = Exception.class)
public ResponseEntity exceptionHandler(Exception e) {
log.error("服务错误:", e);
return ResponseEntity.fail("xxx", "服务出错");
}

/**
* 处理 QDSException 异常
     *
* @param e
* @param e 异常
* @return
*/
@ExceptionHandler(value = QDSException.class)
public ResponseEntity businessExceptionHandler(QDSException e) {
log.error("业务异常。code:" + e.getCode() + "msg:" + e.getMsg());
return ResponseEntity.fail(e.getCode(), e.getMsg());
}
}

2.2 扩展一下 @RestControllerAdvice还可以指定拦截哪些

 技术图片

 

 



2.3创建一个异常返回的实体bean

@Data
public class ResponseEntity implements Serializable {
private String code;
private String msg;
private Object data;

public ResponseEntity() {
}


public ResponseEntity(String code, String msg, Object data) {
this.code = code;
this.msg = msg;
this.data = data;
}

public ResponseEntity( String msg,Object data) {
this.msg = msg;
this.data = data;
}

public static ResponseEntity success(String msg,String data) {
return SUCCESS(msg,data);
}
public static ResponseEntity fail(String code,String msg) {
return FAIL(code,msg);
}

public static ResponseEntity SUCCESS(String msg,Object data) {
return new ResponseEntity(msg,data);
}
public static ResponseEntity FAIL(String msg,Object data) {
return new ResponseEntity(msg,data);
}
}
 

springboot + @ControllerAdvice + @ExceptionHandler 实现全局异常拦截,不用

标签:size   不用   tco   使用   异常   实体   创建   hand   success   

原文地址:https://www.cnblogs.com/bt2882/p/12916104.html


评论


亲,登录后才可以留言!