【问题标题】:Springboot exception handling when there is no controllers没有控制器时的 Spring Boot 异常处理
【发布时间】:2021-04-13 02:23:30
【问题描述】:
我有一个没有任何控制器类的 spring-boot 应用程序。
如何为此应用程序编写异常处理程序。使用 @ControllerAdvice 注释的异常处理程序类不起作用。
【问题讨论】:
-
ExceptionHandler 和 ControllerAdvice 用于处理控制器级别的异常。对于方法级别的异常处理,您必须使用经典的 try/catch 块。参考ekiras.com/2016/02/…
标签:
spring-boot
exception
【解决方案1】:
如果您正在开发web applications,ErrroController 可用。
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class MyErrorController implements ErrorController {
private final ErrorAttributes errorAttributes;
public MyErrorController(final ErrorAttributes errorAttributes) {
this.errorAttributes = errorAttributes;
}
@Override
public String getErrorPath() {
return null;
}
@RequestMapping
public ResponseEntity<Map<String, Object>> error(final HttpServletRequest request) {
final WebRequest webRequest = new ServletWebRequest(request);
final Throwable th = errorAttributes.getError(webRequest);
// ...
// see also: BasicErrorController implementation
}
}