全局攔截自定義的異常

  • 添加一個自定義的異常類MyException繼承Exception
public class BusinessException extends Exception {
    private int code;
    private String massage;

    public BusinessException(int code,String message) {
        this.massage = message;
        this.code = code;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMassage() {
        return massage;
    }

    public void setMassage(String massage) {
        this.massage = massage;
    }
}
  • 添加一個全局的異常處理器處理異常
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * http 417 指望失敗
     * code 1003 認證數量須爲在模板的限定範圍
     */
    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<?> BusinessExceptionHandler(BusinessException e){
        CommonUtils.errorLog(e,logger);//打印異常信息
        return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new Error(new Date(), e.getCode(), e.getMessage()));
    }
}
  • 在須要拋異常的地方throw一下
    @ResponseBody
    @GetMapping("product/page")
    public PageModel<Product> productPage(PageModel pageModel) throws BusinessException {
        System.out.println(123);
        if(true){
            throw new BusinessException(909,"myException");
        }
        return productService.findAll(pageModel);
    }
相關文章
相關標籤/搜索