欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot:ControllerAdvice

程序员文章站 2022-06-16 08:05:04
...
全局异常拦截
//@ControllerAdvice(annotations=TestController.class)
//@ControllerAdvice(basePackages={"com.aaa","com.bbb"})
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ServiceException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    //    @ExceptionHandler(value={RuntimeException.class,MyRuntimeException.class})
    //    @ExceptionHandler//处理所有异常
    @ResponseBody
    public APIResponse handleException(HttpServletRequest request, Exception ex) {
        String message = ex.getMessage();
        return APIResponse.build(HttpStatus.INTERNAL_SERVER_ERROR.value(), message);
    }

//    @ExceptionHandler(SQLException.class)
//    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
//    @ResponseBody
//    public APIResponse handleSQLException(HttpServletRequest request, Exception ex) {
//        String message = ex.getMessage();
//        return APIResponse.build(HttpStatus.INTERNAL_SERVER_ERROR.value(), message);
//    }

//    @ResponseStatus(value=HttpStatus.NOT_FOUND, reason="IOException occured")
//    @ExceptionHandler(IOException.class)
//    @ResponseBody
//    public void handleIOException(){
//        //returning 404 error code
//    }
//
//    @ResponseStatus(HttpStatus.BAD_REQUEST)
//    @ResponseBody
//    @ExceptionHandler(SignException.class)
//    public APIResponse signException(SignException ex) {
//        return ex.getEr();
//    }

}