In the example above, @ControllerAdvice
mapping to different error handling pages by unifying the different exception is defined. And when we want to implement the RESTful API, the error returned is JSON-formatted data, not HTML pages, which we can easily support.
Essentially, @ExceptionHandler
@ResponseBody
you can convert the contents of the return of the handler function into JSON format simply by adding it later.
The following is a concrete example to implement exception handling that returns JSON format.
- Create a unified JSON return object, code: Message type, message: Content, URL: Requested url,data: Request returned data
Public classErrorinfo<t> { Public Static FinalInteger OK = 0; Public Static FinalInteger ERROR = 100; PrivateInteger Code; PrivateString message; PrivateString URL; PrivateT data; //omit getter and setter }
Create a custom exception to experiment with catching the exception and return the JSON
Public class extends Exception { public myexception (String message) { Super(message); } }
Controller
Add JSON mappings, throw MyException
exceptions
@Controller Public class Hellocontroller { @RequestMapping ("/json") publicthrows myexception { thrownew myexception ("Error 2 occurred"); } }
MyException
create a corresponding processing for an exception
@ControllerAdvice Public classGlobalexceptionhandler {@ExceptionHandler (value= MyException.class) @ResponseBody PublicErrorinfo<string> Jsonerrorhandler (httpservletrequest req, myexception e)throwsException {errorinfo<String> r =NewErrorinfo<>(); R.setmessage (E.getmessage ()); R.setcode (Errorinfo.error); R.setdata ("Some Data"); R.seturl (Req.getrequesturl (). toString ()); returnR; } }
Launch app, Access: Http://localhost:8080/json, you can get the following return content:
{ "Some Data", "error 2" , "Http://localhost:8080/json" }
Source source technical support for complete projects 1791743380
Spring Cloud Spring Boot mybatis distributed micro-service Cloud architecture returns JSON format