异常

如果在请求映射期间发生异常或从请求处理程序(例如 一个@Controller)、DispatcherServlet委托到链HandlerExceptionResolverbean 来解决异常并提供替代处理,这通常是error 响应。spring-doc.cadn.net.cn

下表列出了可用的HandlerExceptionResolver实现:spring-doc.cadn.net.cn

表 1.HandlerExceptionResolver 实现
HandlerExceptionResolver 描述

SimpleMappingExceptionResolverspring-doc.cadn.net.cn

异常类名称和错误视图名称之间的映射。对于渲染浏览器应用程序中的错误页面很有用。spring-doc.cadn.net.cn

DefaultHandlerExceptionResolverspring-doc.cadn.net.cn

解决 Spring MVC 引发的异常并将它们映射到 HTTP 状态代码。另请参阅替代ResponseEntityExceptionHandler错误响应spring-doc.cadn.net.cn

ResponseStatusExceptionResolverspring-doc.cadn.net.cn

使用@ResponseStatus注释并将它们映射到 HTTP 状态代码。spring-doc.cadn.net.cn

ExceptionHandlerExceptionResolverspring-doc.cadn.net.cn

通过调用@ExceptionHandler方法@Controller@ControllerAdvice类。 请参阅@ExceptionHandler方法spring-doc.cadn.net.cn

解析器链

您可以通过声明多个HandlerExceptionResolverbean 并设置其order属性。order 属性越高,异常解析器的位置就越晚。spring-doc.cadn.net.cn

合同HandlerExceptionResolver指定它可以返回:spring-doc.cadn.net.cn

MVC 配置自动声明默认 Spring MVC 的内置解析器exceptions,对于@ResponseStatus带注释的异常,并支持@ExceptionHandler方法。 您可以自定义该列表或替换它。spring-doc.cadn.net.cn

容器错误页面

如果异常仍未被任何HandlerExceptionResolver因此,并且是left 以传播,或者如果响应状态设置为错误状态(即 4xx、5xx),Servlet 容器可以在 HTML 中呈现默认错误页面。要自定义容器的默认error 页面,您可以在web.xml. 以下示例显示了如何执行此作:spring-doc.cadn.net.cn

<error-page>
	<location>/error</location>
</error-page>

给定前面的示例,当异常冒泡或响应具有错误状态时,Servlet 容器在容器内对配置的 URL 进行 ERROR 分派(例如,/error). 然后由DispatcherServlet,可能会将其映射到@Controller,可以实现以返回带有模型的错误视图名称或呈现 JSON 响应,如以下示例所示:spring-doc.cadn.net.cn

@RestController
public class ErrorController {

	@RequestMapping(path = "/error")
	public Map<String, Object> handle(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<>();
		map.put("status", request.getAttribute("jakarta.servlet.error.status_code"));
		map.put("reason", request.getAttribute("jakarta.servlet.error.message"));
		return map;
	}
}
@RestController
class ErrorController {

	@RequestMapping(path = ["/error"])
	fun handle(request: HttpServletRequest): Map<String, Any> {
		val map = HashMap<String, Any>()
		map["status"] = request.getAttribute("jakarta.servlet.error.status_code")
		map["reason"] = request.getAttribute("jakarta.servlet.error.message")
		return map
	}
}
Servlet API 不提供在 Java 中创建错误页面映射的方法。 您可以 但是,请同时使用WebApplicationInitializer和最小的web.xml.