spring 全局异常处理

  1. @RestControllerAdvice+@ExceptionHandler可用于处理所有controller抛出的异常(包括抛出的编译时异常与运行时异常)。
  2. @RestControllerAdvice = @ControllerAdvice+@ResponseBody。
  3. @ExceptionHandler({HttpMessageNotReadableException.class,MethodArgumentNotValidException.class})可以处理单个异常,也可以处理多个。
  4. @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);
    }
}

 

posted @ 2018-03-16 16:55  扶不起的刘阿斗  阅读(156)  评论(0编辑  收藏  举报