Global interception abnormal custom

  • Add MyException exception classes inherit a custom 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;
    }
}
  • Add a global exception handler Exception
@ControllerAdvice
public class GlobalExceptionHandler {

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

    /**
     * Http 417 expectation failed
     * Code number 1003 shall limit the scope of the authentication template
     */
    @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()));
    }
}
  • In need abnormal place throw throw about
    @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);
    }

 

Guess you like

Origin www.cnblogs.com/erfsfj-dbc/p/11756477.html