Spring Cloud Spring Boot mybatis distributed microservice cloud architecture (12) returns JSON format

In the above example, @ControllerAdvicedifferent Exceptions are mapped to different error handling pages by uniformly defining them. When we want to implement a RESTful API, the error returned is JSON formatted data, not HTML pages, which we can easily support at this time.

Essentially, just add it @ExceptionHandlerlater to @ResponseBodyconvert the content of the handler function return to JSON format.

The following uses a specific example to implement the exception handling that returns JSON format.

  • Create a unified JSON return object, code: message type, message: message content, url: requested url, data: data returned by the request
    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 experimentally capture the exception and return json
    public class MyException extends Exception {
    
        public MyException(String message) {
            super(message);
        }
        
    }

     

  • ControllerAdd json mapping in , throw MyExceptionexception
    @Controller
    public class HelloController {
    
        @RequestMapping("/json")
        public String json() throws MyException {
            throw new MyException("发生错误2");
        }
    
    }

     

  • Create corresponding handlers for MyExceptionexceptions
    @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;
        }
    
    }
    

     

  • Start the application and visit: http://localhost:8080/json, you can get the following return content :
  • {
        code: 100,
        data: "Some Data",
        message: "发生错误2",
        url: "http://localhost:8080/json"
    }

    So far, the creation of unified exception handling in Spring Boot has been completed. The actual implementation still relies on Spring MVC annotations. For more in-depth use, please refer to the Spring MVC documentation.

  • source code

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325339331&siteId=291194637