This is the 19th day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021
== This article is based on Rest API, return error message is JSON data! The console will still print an exception log == complete project address: github.com/Dr-Water/sp…
1. Springboot’s default exception handling is very ugly: for example:
2. We can use the @ControllerAdvice annotation of springMVC to implement global exception handling and unify the return format of exceptions as follows:
1. Create uniform JSON return objects: code: message type, message: message content, URL: REQUEST URL, and data: returned data
@Data
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;
}
Copy the code
2. Create a custom exception, use it to catch the exception, and return JSON
public class MyException extends Exception {
public MyException(String message) {
super(message); }}Copy the code
3. Add JSON mapping to Controller and throw MyException
@RestController
public class HelloController {
/** Used to test custom exceptions *@return
* @throws Exception
*/
@RequestMapping("/json")
public String json(a) throws Exception {
throw new MyException("Error la la la la la");
}
/** Used to test exceptions other than custom exceptions *@return* /
@RequestMapping("/json2")
public Integer json2(a){
return 2/0; }}Copy the code
4. Define exception handlers:
@ControllerAdvice
public class GlobalExceptionHandler {
/** * The largest exception catching class, the handler for last-pocket exceptions *@param req
* @param e
* @return
* @throws Exception
*/
@ExceptionHandler(value = Exception.class)
@ResponseBody
public ErrorInfo<String> jsonErrorHandler(HttpServletRequest req, Exception 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;
}
/** * is used to catch a custom exception. A custom exception can have more than one handler. When an exception occurs, if the custom exception is matched, it will not match the largest exception handler above (i.e., jsonErrorHandler) *@param req
* @param e
* @return
* @throws Exception
*/
@ExceptionHandler(value = MyException.class)
@ResponseBody
public ErrorInfo<String> myjsonErrorHandler(HttpServletRequest req, MyException e) throws Exception {
ErrorInfo<String> r = new ErrorInfo<>();
r.setMessage(e.getMessage());
r.setCode(ErrorInfo.ERROR);
r.setData("Some Data====myjsonErrorHandler");
r.setUrl(req.getRequestURL().toString());
returnr; }}Copy the code
5. Test
Start the application for test access:http://localhost:8080/jsonThe following result is returned: http://localhost:8080/json2The following result is returned:The first graph, because it is a custom exception thrown, returns data encapsulated by the custom exception handler, namely: ==Some Data====myjsonErrorHandler==, the second graph is blocked by maximum exception by default because of an arithmetic exception thrown, so the last Data in the Data is: ==”Some Data”==