@ExceptionHandler
Spring学习笔记_40——@RequestHeader
Spring学习笔记_41——@RequestBody
Spring学习笔记_42——@CookieValue
1. 介绍
@ExceptionHandler
是 Spring 框架中用于处理控制器方法中发生的异常的一个注解。它允许开发者定义一个或多个方法来集中处理由控制器内方法抛出的特定异常类型。通过这种方式,可以将错误处理逻辑与业务逻辑分离,使得代码更加清晰、易于维护。
2. 场景
如果在基于SpringMVC或者SpringBoot开发应用程序时,想统一捕获并处理一场信息,就可以使用@ExceptionHandler
3. 源码
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Reflective(ExceptionHandlerReflectiveProcessor.class)
public @interface ExceptionHandler {
// Class数组类型的属性,主要用于指定捕获的异常类型
Class<? extends Throwable>[] value() default {};
}
4. Demo
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(NullPointerException.class)
public ResponseEntity<String> handleNullPointerException(NullPointerException ex) {
return new ResponseEntity<>("Null Pointer Exception Occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String> handleResourceNotFoundException(ResourceNotFoundException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
}
@RestController
public class ExceptionHandlerController {
@RequestMapping(value= "/hello")
public String hello(String name) {
int i = 1 / 0;
return "hello " + name
}
@ExceptionHandler(value = Exception.class)
public String handlerException(Exception e) {
return "exception info is: " + e.getMessage();
}
}