SpringMVC中@RestControllerAdvice统一异常处理


GlobalExceptionHandler为统一异常处理类,MyException自定义异常类,
@RestControllerAdvice相当于Controller的切面,对异常统一处理,定制,这样更好返回给前端。
@RestControllerAdvice
public class GlobalExceptionHandler {
    public GlobalExceptionHandler(){}
    @ExceptionHandler({MyException.class})
    public ResponseEntity<ResErr> handleMyException(MyException ex){
        ResErr resErr=new ResErr();
        resErr.setErrCode(12344);
        resErr.setErrMsg(ex.getMessage());
        return new ResponseEntity<>(resErr, HttpStatus.OK);
    }
    @ExceptionHandler({RuntimeException.class})
    public ResponseEntity<ResErr> handleMyException(RuntimeException ex){
        ResErr resErr=new ResErr();
        resErr.setErrCode(99999);
        resErr.setErrMsg("运行时异常");
        return new ResponseEntity<>(resErr, HttpStatus.OK);
    }
    @ExceptionHandler({Exception.class})
    public ResponseEntity<ResErr> handleMyException(Exception ex){
        ResErr resErr=new ResErr();
        resErr.setErrCode(99999);
        resErr.setErrMsg("系统异常");
        return new ResponseEntity<>(resErr, HttpStatus.OK);
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM