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