In the above example, the @controlleradvice unified definition of different exception maps to different error handling pages. 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, by adding @responsebody after @exceptionhandler, you can convert the contents of the return of the handler function into JSON format.
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
[Java] View plain copy
public class Errorinfo<t> {
public static final Integer OK = 0; public static final Integer ERROR = 100; private Integer code; private String message; private String url; private T data; // 省略getter和setter
}
Create a custom exception to experiment with catching the exception and return the JSON
[Java] View plain copy
public class MyException extends Exception {
public MyException(String message) { super(message); }
}
Add JSON mapping in controller, throw MyException exception
[Java] View plain copy
@Controller
public class Hellocontroller {
@RequestMapping("/json") public String json() throws MyException { throw new MyException("发生错误2"); }
}
Create a corresponding processing for a myexception exception
[Java] View plain copy
@ControllerAdvice
public class Globalexceptionhandler {
@ExceptionHandler(value = MyException.class) @ResponseBody public ErrorInfo<String> jsonErrorHandler(HttpServletRequest req, MyException e) throws Exception { ErrorInfo<String> r = new ErrorInfo<>(); r.setMessage(e.getMessage()); r.setCode(ErrorInfo.ERROR); r.setData("Some Data"); r.setUrl(req.getRequestURL().toString()); return r; }
}
Launch app, Access: Http://localhost:8080/json, you can get the following return content:
[Java] View plain copy
{
CODE:100,
Data: "Some data",
Message: "Error 2 occurred",
URL: "Http://localhost:8080/json"
}
Now that you have finished creating uniform exception handling in spring boot, the actual implementation is still dependent on spring MVC annotations, and more in-depth use can refer to the documentation for spring MVC.
Spring Cloud Spring Boot mybatis distributed micro-service Cloud Architecture (12)