异常处理
@Controller 和 [ControllerAdvice](ann-advice.md) 类可以拥有 @ExceptionHandler 方法来处理来自控制器方法的异常。以下示例包含这样一个处理器方法:
- Java
- Kotlin
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),也可以匹配到顶级包装异常中的直接原因(例如,封装在 IllegalStateException 内的 IOException)。
为了匹配异常类型,最好将目标异常声明为方法参数,如前面的示例所示。或者,也可以通过注解声明来缩小需要匹配的异常类型范围。我们通常建议在参数签名中尽可能具体地说明异常类型,并将主要的根异常映射声明在@ControllerAdvice上,并按相应的优先级排序。详细信息请参见MVC部分。
WebFlux 中的 @ExceptionHandler 方法支持与 @RequestMapping 方法相同的方法参数和返回值,但请求体(request body)相关的参数以及 @ModelAttribute 相关的参数除外。
在Spring WebFlux中,对@ExceptionHandler方法的支持是通过HandlerAdapter为@RequestMapping方法提供的。有关更多详细信息,请参阅DispatcherHandler。
媒体类型映射
除了异常类型之外,@ExceptionHandler 方法还可以声明可生成的媒体类型。这使得可以根据 HTTP 客户端请求的媒体类型(通常在“Accept”HTTP 请求头中指定)来细化错误响应。
应用程序可以直接在注释中声明可产生的媒体类型,对于相同的异常类型也是如此:
- Java
- Kotlin
@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错误页面。每个@ExceptionHandler注解可以声明多种可生成的媒体类型,在错误处理阶段的内容协商将决定使用哪种内容类型。
方法参数
@ExceptionHandler 方法支持与 @RequestMapping 方法相同的 方法参数,不同之处在于请求体可能已经被处理掉了。
返回值
@ExceptionHandler 方法支持的返回值与@RequestMapping方法相同。