Reputation: 4441
How can I return a simple text String like below, basically I want to display a simple text for my error in the browser.
I handle my error in here and here I want to do it:
@ExceptionHandler(Exception.class)
public ModelAndView handleAllException(Exception e) {
}
The problem is I have to return a ModelAndView. How can I return a simple text to the browser, do not want to use any JSP etc.
Just return the same way like below or similar:
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
For example this does not work:
return new ModelAndView((View) ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage()));
Upvotes: 2
Views: 1271
Reputation: 125
You could do:
public ModelAndView handleAllException(Exception e) {
ModelAndView mav = new ModelAndView("your_jsp_name");
modelAndView.addObject("name", "Peter");
...
return mav;
}
Upvotes: -2
Reputation: 955
From the @ExceptionHandler
documentation:
Handler methods which are annotated with this annotation are allowed to have very flexible signatures. They may have parameters of the following types, in arbitrary order: [...] OutputStream / Writer for generating the response's content. This will be the raw OutputStream/Writer as exposed by the Servlet API. [...]
So you could define an exception handling method which looks something like this:
@ExceptionHandler(Exception.class)
public void handleAllException(Exception e, Writer responseWriter) {
responseWriter.write(e.getMessage());
}
You can obviously do something more complex to format the error message, but that's the basic idea.
Upvotes: 3