0

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 enter image description here

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.

Hayk Mkhitaryan
  • 388
  • 9
  • 26

3 Answers3

0

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;
  }
}
Rodrigo Silva
  • 463
  • 3
  • 10
-1

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

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

Ivan Dimitrov
  • 332
  • 1
  • 10
  • it is not spring boot application, it is mvc, and not rest, if I do like you are showing, I will not get the required error field populated, only will give status to client, but I need to give also the error and status. – Hayk Mkhitaryan Jul 15 '20 at 07:46
  • Try this : https://stackoverflow.com/questions/16232833/how-to-respond-with-http-400-error-in-a-spring-mvc-responsebody-method-returnin – Ivan Dimitrov Jul 15 '20 at 15:06
-1

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

@ExceptionHandler({ Throwable.class })
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String handleError(...) {
   ...
}
Bala
  • 1,295
  • 1
  • 12
  • 23
  • I did like you said, but anyway, it returns 500, – Hayk Mkhitaryan Jul 14 '20 at 15:57
  • Not sure why it didn't work. Do you have @ExceptionHandler on your method. Can you try updated answer once. And also were you able to debug and is debugger point entering into this method? – Bala Jul 17 '20 at 07:26