基于springboot实现全局异常处理
声明:本人并不具备详细解析这个过程的具体实现,我将介绍如何使用,及我的一些个人理解。
场景:后端返回信息,前端可以根据后端数据返回的“错误”信息给予用户更好的体验
逻辑说明:首先创建一个自定义异常类继承RuntimeException(不需要捕获),我的例子是“BusinessException”,将业务信息与异常类分离,创建一个枚举类“BusinessExceptionCode”,枚举业务异常信息。创建一个异常处理框架,“ControllerExceptionHandler”,通过spring注解@ControllerAdvice注入容器,这个注解使得它的成员方法可以拥有@ExceptionHandler注解的方法,这些方法会被应用到controller类层次,所以也就会处理相关控制器类中抛出的异常。
补充说明:异常处理也要处理一些我们未处理的Expection,因此ControllerExceptionHandler中还有一个处理Expection的异常。Commresp是我设置的返回类,如果有需要自己替换返回类。
基本框架
BusinessException
public class BusinessException extends RuntimeException{
private BusinessExceptionCode code;
public BusinessException(BusinessExceptionCode code) {
super(code.getDesc());
this.code = code;
}
public BusinessExceptionCode getCode() {
return code;
}
public void setCode(BusinessExceptionCode code) {
this.code = code;
}
@Override
public Throwable fillInStackTrace() {
return this;
}
}
BusinessExceptionCode
public enum BusinessExceptionCode {
LOGIN_EXCEPTION("登录出错"),
SYSTEM_ERROR("系统错误")
;
private String desc;
BusinessExceptionCode(String desc) {
this.desc = desc;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
ControllerExceptionHandler
@ControllerAdvice
public class ControllerExceptionHandler {
@ExceptionHandler(value = BusinessException.class)
@ResponseBody
public CommonResp validExceptionHandler(BusinessException e) {
CommonResp commonResp = new CommonResp();
commonResp.setSuccess(false);
commonResp.setMessage(e.getCode().getDesc());
return commonResp;
}
@ExceptionHandler(value = Exception.class)
@ResponseBody
public CommonResp validExceptionHandler(Exception e) {
CommonResp commonResp = new CommonResp();
commonResp.setSuccess(false);
commonResp.setMessage("系统异常,请联系管理员");
return commonResp;
}
}
Commresp
public class CommonResp<T> {
/**
* 业务上的成功或失败
*/
private boolean success = true;
/**
* 返回信息
*/
private String message;
/**
* 返回泛型数据,自定义类型
*/
private T content;
public T getContent() {
return content;
}
public void setContent(T content) {
this.content = content;
}
public CommonResp() {
}
public CommonResp(String message, T content) {
this.message = message;
this.content = content;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("ResponseDto{");
sb.append("success=").append(success);
sb.append(", message='").append(message).append('\'');
sb.append(", content=").append(content);
sb.append('}');
return sb.toString();
}
}
如何使用,简单demo
说明:我们只需要抛出自定义异常,我这里未使用mapper,因为这只是个小demo,mapper层与异常处理无多大相关关系,我们只需要根据参数和mapper类返回的数据进行异常处理即可。
controller
@RestController
public class DemoController {
@Resource
private DemoService demoService;
@GetMapping("/demo")
public void demo(){
demoService.demo();
}
@GetMapping("/demo1")
public CommonResp demo1(){
demoService.demo();
return new CommonResp();
}
}
service
@Service
public class DemoService {
public void demo(){
if(1 == 0){//某种情况
throw new BusinessException(BusinessExceptionCode.LOGIN_EXCEPTION);
}
System.out.println("业务正常进行");
}
}