异常
@Controller
@ControllerAdvice类可以具有@ExceptionHandler
方法处理来自控制器方法的异常。以下内容
example 包含这样的处理程序方法:
-
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
被抛出)或针对顶级包装器中的直接原因
exception(例如,IOException
包装在IllegalStateException
).
对于匹配的异常类型,最好将目标异常声明为方法参数,
如前面的示例所示。或者,注释声明可以缩小
异常类型进行匹配。我们通常建议在
参数签名,并在@ControllerAdvice
prioritizeed 和相应的顺序。
有关详细信息,请参阅 MVC 部分。
一@ExceptionHandler method 支持相同的方法参数和
将值作为@RequestMapping 方法,请求正文除外 -
和@ModelAttribute -相关的方法参数。 |
支持@ExceptionHandler
方法由HandlerAdapter
为@RequestMapping
方法。看DispatcherHandler
了解更多详情。
媒体类型映射
除了异常类型之外,@ExceptionHandler
方法还可以声明可制作的媒体类型。
这允许根据 HTTP 客户端请求的媒体类型(通常在 “Accept” HTTP 请求标头中)来优化错误响应。
对于相同的异常类型,应用程序可以直接在 Comments 上声明可制作的媒体类型:
-
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
annotation 可以声明几种可制作的媒体类型,
错误处理阶段的内容协商将决定将使用哪种内容类型。
方法参数
@ExceptionHandler
方法支持与@RequestMapping
方法,但请求正文可能已被使用。
返回值
@ExceptionHandler
方法支持与@RequestMapping
方法。