首页 > 解决方案 > 带有响应状态代码的 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。所以,请帮助我,如何克服这个问题。

标签: javaspringspring-mvc

解决方案


你可以扩展你的异常并将它们扔到你的控制器上:

@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;
  }
}

推荐阅读