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