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

Posted 写尽千帆

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot + @ControllerAdvice + @ExceptionHandler 实现全局异常拦截,不用相关的知识,希望对你有一定的参考价值。

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(200, "服务出错");
}

/**
* 处理 BusinessException 异常
*
* @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 Integer code;
private String msg;
private Object data;

public ResponseEntity() {
}


public ResponseEntity(Integer 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 ResponseEntity( Integer code,String msg) {
this.code = code;
this.msg = msg;
}

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

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


2.3创建一个自定义异常类

@Data
public class QDSException extends RuntimeException {
private Integer code;
private String msg;
private Object data;

public QDSException(String msg) {
this.msg= msg;
}
public QDSException(Integer code,String msg) {
this.code = code;
this.msg= msg;
}

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

2.4 接下来我们postman测试一下就可以了

@RestController
public class MyController {

@RequestMapping(value = "/test2")
public ResponseEntity test2() {
throw new QDSException(5005,"错误");
}
}

 

2.5 如果我们抛出没有拦截的异常打印出堆栈信息


以上是关于springboot + @ControllerAdvice + @ExceptionHandler 实现全局异常拦截,不用的主要内容,如果未能解决你的问题,请参考以下文章

视图控制器传值

iOS:检测触地、segue、触地

更改单个 ASP.NET Core 控制器的 JSON 序列化设置

覆盖angularjs

iOS工作笔记

JavaEE学习之旅---->SpringMVC