此版本仍在开发中,尚未稳定。如需最新的稳定版本,请使用 Spring Framework 7.0.6spring-doc.cadn.net.cn

异常

@Controller@ControllerAdvice 类可以包含 @ExceptionHandler 方法来处理控制器方法中的异常。以下示例包含了一个这样的处理器方法: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)或顶级包装异常中的直接原因(例如,IOException 被封装在 IllegalStateException 中)。spring-doc.cadn.net.cn

对于匹配的异常类型,最好将目标异常声明为方法参数,如前面的例子所示。或者,注解声明可以缩小匹配的异常类型。我们通常建议在参数签名中尽可能具体,并将主要根异常映射声明为优先级@ControllerAdvice,并设置相应的顺序。 请参见MVC部分以获取详细信息。spring-doc.cadn.net.cn

An @ExceptionHandler 方法在 WebFlux 中支持与 @RequestMapping 方法相同的参数和返回值,但不包括与请求正文和 @ModelAttribute 相关的参数。

Spring WebFlux 中对 @ExceptionHandler 方法的支持由 HandlerAdapter@RequestMapping 方法提供。有关详细信息,请参阅 DispatcherHandlerspring-doc.cadn.net.cn

媒体类型映射

除了异常类型外,@ExceptionHandler 方法还可以声明可产生的媒体类型。这允许根据HTTP客户端请求的媒体类型(通常在“Accept”HTTP请求头中)来细化错误响应。spring-doc.cadn.net.cn

应用程序可以直接在注解上声明可生产的媒体类型,针对相同的异常类型: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"
}

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

方法参数

@ExceptionHandler个方法支持与@RequestMapping个方法相同的方法参数,但请求体可能已被消耗。spring-doc.cadn.net.cn

返回值

@ExceptionHandler个方法支持与@RequestMapping个方法相同的返回值spring-doc.cadn.net.cn