java全局异常处理
在项目中,我们需要对各种异常进行处理,但是我们又不知道什么时候发生异常,而对每个方法进行捕获这个也不太现实这个时候就需要我们对项目中的异常进项全局的处理,下面是在我一个小型博客项目中对全局异常的处理。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 
 | 
 
 
 @Slf4j
 @RestControllerAdvice
 public class GlobalExceptionHandler {
 @ResponseStatus(HttpStatus.UNAUTHORIZED)
 @ExceptionHandler(value = ShiroException.class)
 public Result handler(ShiroException e){
 log.error("运行时异常------------------{}",e);
 return Result.failed(401,e.getMessage());
 }
 @ResponseStatus(HttpStatus.BAD_REQUEST)
 @ExceptionHandler(value = IllegalArgumentException.class)
 public Result handler(IllegalArgumentException e){
 log.error("Assert异常------------------{}",e);
 return Result.failed(e.getMessage());
 }
 @ResponseStatus(HttpStatus.BAD_REQUEST)
 @ExceptionHandler(value = MethodArgumentNotValidException.class)
 public Result handler(MethodArgumentNotValidException e){
 log.error("实体校验异常------------------{}",e);
 BindingResult result = e.getBindingResult();
 ObjectError objectError = result.getAllErrors().stream().findFirst().get();
 return Result.failed(objectError.getDefaultMessage());
 }
 @ResponseStatus(HttpStatus.BAD_REQUEST)
 @ExceptionHandler(value = RuntimeException.class)
 public Result handler(RuntimeException e){
 log.error("运行时异常------------------{}",e);
 return Result.failed(e.getMessage());
 }
 }
 
 | 
