java - 带有响应状态代码的 Spring MVC 错误处理
问题描述
请在这个问题上帮助我。我正在从事的项目是旧的 mvc,不会更改为休息,因此必须处理“我们拥有的 :)”。这是我的控制器方法,其类已注释@Controller
@RequestMapping(method=RequestMethod.POST)
public String createSomething(@RequestBody somejson, Model m) throws Exception {
SomeCustomListenerClass listener = new SomeCustomListenerClass(m);
AnnotherClass ac = somejson.toNotification(someService, anotherService, listener);
try {
ac = someService.createSomething(ac, listener);
m.addAttribute("success", true);
m.addAttribute("notificationId", ac.getId());
}
catch(SawtoothException ex) {
return handleError(ex, "Create Notification", listener);
}
return "structured";
}
这个是handleError方法体
private String handleError(Exception ex, String operation, SomeCustomListenerClass listener) {
if (!listener.hasErrors()) {
log.error("Unexpected error getting notification detail", ex);
listener.error("notification.controllerException", operation);
}
return "error";
}
现在我在客户端得到了正确的错误,比如在浏览器中,但也得到了状态码 500
现在我的老板说当验证错误发生时我们必须得到 400,而不是现在的 500。所以,请帮助我,如何克服这个问题。
解决方案
你可以扩展你的异常并将它们扔到你的控制器上:
@ResponseStatus(value=HttpStatus.BAD_REQUEST, reason="Your exception message")
public class YourCustomException extends RuntimeException {
}
或者您可以使用 ExceptionControllerHandler:
@Controller
public class ExceptionHandlingController {
// @RequestHandler methods
...
// Exception handling methods
// Convert a predefined exception to an HTTP Status code
@ResponseStatus(value=HttpStatus.CONFLICT,
reason="Data integrity violation") // 409
@ExceptionHandler(DataIntegrityViolationException.class)
public void conflict() {
// Nothing to do
}
// Specify name of a specific view that will be used to display the error:
@ExceptionHandler({SQLException.class,DataAccessException.class})
public String databaseError() {
// Nothing to do. Returns the logical view name of an error page, passed
// to the view-resolver(s) in usual way.
// Note that the exception is NOT available to this view (it is not added
// to the model) but see "Extending ExceptionHandlerExceptionResolver"
// below.
return "databaseError";
}
// Total control - setup a model and return the view name yourself. Or
// consider subclassing ExceptionHandlerExceptionResolver (see below).
@ExceptionHandler(Exception.class)
public ModelAndView handleError(HttpServletRequest req, Exception ex) {
logger.error("Request: " + req.getRequestURL() + " raised " + ex);
ModelAndView mav = new ModelAndView();
mav.addObject("exception", ex);
mav.addObject("url", req.getRequestURL());
mav.setViewName("error");
return mav;
}
}
推荐阅读
- c - 编写ac函数,检查一个int数组是否只包含1和2
- javascript - Netlify 向 HTTP 发出 HTTPS 请求
- flutter - '未来的实例
' - javascript - 根据生成的元素的可变数量创建一组 div
- appium-ios - 由于 xcodebuild 失败,无法启动 WebDriverAgent:命令 'carthage bootstrap --platform iOS\,tvOS' exited with code 1
- swift - 如何在 SwiftUI 中制作斜体圆形样式系统文本?
- java - Android Studio,更改 MP BarChart 数据时应用程序崩溃
- scala - Akka gRPC/HTTP Interop 给出 404
- reactjs - 如何使链接出现在我制作的组件上方?
- django - 在 heroku 中更改 DATABASE_URL