简体   繁体   中英

Spring MVC error handling with response status code

help me anybody Please in this issue. The project, I am working on is old mvc, and is not going to be change to rest, So have to deal with "what we have:) ". this is my controller method, the class of which is anotated @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";
}

and this one is handleError method body

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

Now I am getting the right errors in the client side, say in browser, but also getting the status code 500 在此处输入图像描述

now my boss says that we have to get 400, when validation errors hapens, not 500, as is now. So, Please help me guys, how to overcome to this problem.

You can extend your exceptions and throw them on your controller:

@ResponseStatus(value=HttpStatus.BAD_REQUEST, reason="Your exception message")  
public class YourCustomException extends RuntimeException {
}

Or you can use an 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;
  }
}

Try the @ExceptionHandler annotation or @ControllerAdvice to create custom exception handling mechanisms:

https://www.tutorialspoint.com/spring_boot/spring_boot_exception_handling.htm

add @ResponseStatus(HttpStatus.BAD_REQUEST) on top of handleError(...) method.

@ExceptionHandler({ Throwable.class })
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String handleError(...) {
   ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM