@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);
    }
}

猜你喜欢

转载自www.cnblogs.com/mufeng07/p/12659441.html
今日推荐