对于最新的稳定版本,请使用 Spring Framework 6.2.0spring-doc.cadn.net.cn

异常

@Controller@ControllerAdvice类可以具有@ExceptionHandler方法处理来自控制器方法的异常。以下内容 example 包含这样的处理程序方法:spring-doc.cadn.net.cn

@Controller
public class SimpleController {

	// ...

	@ExceptionHandler (1)
	public ResponseEntity<String> handle(IOException ex) {
		// ...
	}
}
1 声明@ExceptionHandler.
@Controller
class SimpleController {

	// ...

	@ExceptionHandler (1)
	fun handle(ex: IOException): ResponseEntity<String> {
		// ...
	}
}
1 声明@ExceptionHandler.

该异常可以与正在传播的顶级异常(即直接IOException被抛出)或针对顶级包装器中的直接原因 exception(例如,IOException包装在IllegalStateException).spring-doc.cadn.net.cn

对于匹配的异常类型,最好将目标异常声明为方法参数, 如前面的示例所示。或者,注释声明可以缩小 异常类型进行匹配。我们通常建议在 参数签名,并在@ControllerAdviceprioritizeed 和相应的顺序。 有关详细信息,请参阅 MVC 部分spring-doc.cadn.net.cn

@ExceptionHandlermethod 支持相同的方法参数和 将值作为@RequestMapping方法,请求正文除外 - 和@ModelAttribute-相关的方法参数。

支持@ExceptionHandler方法由HandlerAdapter@RequestMapping方法。看DispatcherHandler了解更多详情。spring-doc.cadn.net.cn

方法参数

@ExceptionHandler方法支持与@RequestMapping方法,但请求正文可能已被使用。spring-doc.cadn.net.cn