[英]Spring MVC error handling with response status code
請在這個問題上幫助我。 我正在處理的項目是舊的 mvc,並且不會更改為 rest,因此必須處理“我們擁有的:)”。 這是我的 controller 方法,其中的 class 被注釋為@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。 所以,請幫助我,如何克服這個問題。
您可以擴展您的異常並將它們扔到您的 controller 上:
@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;
}
}
嘗試使用 @ExceptionHandler 注釋或 @ControllerAdvice 來創建自定義異常處理機制:
https://www.tutorialspoint.com/spring_boot/spring_boot_exception_handling.htm
在 handleError(...) 方法之上添加@ResponseStatus( HttpStatus.BAD_REQUEST) 。
@ExceptionHandler({ Throwable.class })
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String handleError(...) {
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.