spring 全局异常处理
- @RestControllerAdvice+@ExceptionHandler可用于处理所有controller抛出的异常(包括抛出的编译时异常与运行时异常)。
- @RestControllerAdvice = @ControllerAdvice+@ResponseBody。
- @ExceptionHandler({HttpMessageNotReadableException.class,MethodArgumentNotValidException.class})可以处理单个异常,也可以处理多个。
- @ResponseStatus(HttpStatus.BAD_REQUEST)用以定义ResponseStatus
例子:
@RestControllerAdvice public class RestException { //可处理运行时异常 @ExceptionHandler({RuntimeException.class}) @ResponseStatus(HttpStatus.UNAUTHORIZED) public String handleRuntimeException(HttpServletRequest req){ return "asdasd"; } //可处理编译时异常 @ExceptionHandler({Exception.class}) public ResponseEntity handleException(HttpServletRequest req , Exception ex) { return new ResponseEntity("Exasdception",HttpStatus.UNAUTHORIZED); } }