此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Framework 6.2.0spring-doc.cadn.net.cn

异常

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

import java.io.IOException;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;

@Controller
public class SimpleController {

	@ExceptionHandler(IOException.class)
	public ResponseEntity<String> handle() {
		return ResponseEntity.internalServerError().body("Could not read file storage");
	}

}
import org.springframework.http.ResponseEntity
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.ExceptionHandler
import java.io.IOException

@Controller
class SimpleController {

	@ExceptionHandler(IOException::class)
	fun handle() : ResponseEntity<String> {
		return ResponseEntity.internalServerError().body("Could not read file storage")
	}
	
}

该异常可以与正在传播的顶级异常(即直接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方法还可以声明可制作的媒体类型。 这允许根据 HTTP 客户端请求的媒体类型(通常在 “Accept” HTTP 请求标头中)来优化错误响应。spring-doc.cadn.net.cn

对于相同的异常类型,应用程序可以直接在 Comments 上声明可制作的媒体类型:spring-doc.cadn.net.cn

@ExceptionHandler(produces = "application/json")
public ResponseEntity<ErrorMessage> handleJson(IllegalArgumentException exc) {
	return ResponseEntity.badRequest().body(new ErrorMessage(exc.getMessage(), 42));
}

@ExceptionHandler(produces = "text/html")
public String handle(IllegalArgumentException exc, Model model) {
	model.addAttribute("error", new ErrorMessage(exc.getMessage(), 42));
	return "errorView";
}
@ExceptionHandler(produces = ["application/json"])
fun handleJson(exc: IllegalArgumentException): ResponseEntity<ErrorMessage> {
	return ResponseEntity.badRequest().body(ErrorMessage(exc.message, 42))
}

@ExceptionHandler(produces = ["text/html"])
fun handle(exc: IllegalArgumentException, model: Model): String {
	model.addAttribute("error", ErrorMessage(exc.message, 42))
	return "errorView"
}

在这里,方法处理相同的异常类型,但不会作为重复项被拒绝。 相反,请求 “application/json” 的 API 客户端将收到 JSON 错误,而浏览器将获得 HTML 错误视图。 每@ExceptionHandlerannotation 可以声明几种可制作的媒体类型, 错误处理阶段的内容协商将决定将使用哪种内容类型。spring-doc.cadn.net.cn

方法参数

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