`
richand730
  • 浏览: 3133 次
社区版块
存档分类
最新评论

SpringBoot添加全局异常

 
阅读更多

编写异常枚举

public enum BizError {
    SYSTEM_ERROR("00000","系统异常"),
    NOT_PERMISSION_ERROR("00001","没有操作权限");

    private final String errorCode;
    private final String errorDesc;

    public String getErrorCode() {
        return errorCode;
    }

    public String getErrorDesc() {
        return errorDesc;
    }

    BizError(String errorCode, String errorDesc){
        this.errorCode = errorCode;
        this.errorDesc = errorDesc;
    }
}

 

自定义异常类

public class TestException extends RuntimeException{
    private String errorMessage;
    private String errorCode;

    public TestException(BizError bizError){
        this.errorCode = bizError.getErrorCode();
        this.errorMessage = bizError.getErrorDesc();
    }

    public JSONObject toJson() {
        return JSONUtil.createObj().put("errorCode",errorCode).put("errorMessage",errorMessage);
    }
}

 

编写异常处理类

@Slf4j
@ControllerAdvice
public class BasicExceptionHandler {

    @ExceptionHandler
    public void handler(Exception e, HandlerMethod handlerMethod, HttpServletResponse response){
        if (e instanceof TestException){
            ResultUtil.responseJson(response,((TestException)e).toJson());
        }else {
            log.error("{} method name: {}() handler error",handlerMethod.getBeanType(),handlerMethod.getMethod().getName(),e);
            ResultUtil.responseJson(response,new TestException(BizError.SYSTEM_ERROR).toJson());
        }
    }
}

 

测试类

@Slf4j
@RestController
public class TestController {
    @GetMapping("/test")
    public String test(int result) throws Exception {
        if (result == 1) {
            log.info("【test2】被执行了。。。。。");
            return "我一直都在,卟离卟弃";
        }
        else if (result == 2){
            throw new TestException(BizError.NOT_PERMISSION_ERROR);
        }
        throw new TestException(BizError.SYSTEM_ERROR);
    }
}
 
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics