SoFunction
Updated on 2025-03-08

Springboot Unified Exception Handling (returning to json) and formatting exceptions

Unified exception handling

When using spring boot to develop backends, we often adopt the development strategy of separation of front-end and backends. At this time, the front-end and backend need to interact with data. Traditionally, json data interaction is generally adopted.

At this time, we need to modify the default exception handling method of spring boot, and we must return the data format uniformly, elegant data interaction, and elegant development and application.

First of all, we need to understand where the general springboot error occurs.

Usually happens incontrollerBusiness layerIn filter (such as spring security)In the interceptor, and that's itUnknown errorNow.

Let me share my handling method:@RestControllerAdvice+filter+Rewrite BasicErrorControllerHow to deal with it.

@RestControllerAdvice

@RestControllerAdvice+@ExceptionHandler() can handle exception errors passing through controller

@RestControllerAdvice
public class BaseExceptionHandler {
    private static final Logger logger = ();
    /**
      * Unknown exception
      * @param e Exception
      * @return Unified result return
      */
    @ExceptionHandler()
    public R exception(Exception e) {
        ((), e);
        return ().message(());
    }
    @ExceptionHandler()
    public R noHandlerFoundException(){
        return ().message("The current page does not exist");
    }
}

filter catches all exceptions

When the error has not passed through the controller, @RestControllerAdvice cannot be captured, and it needs to be processed in the filter.

public class ExceptionHandlerFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain){
        try {
            (servletRequest, servletResponse);
        } catch (Exception e) {
            ((HttpServletResponse) servletResponse, ().message(()));
        }
    }
}

Remember to register filter to springboot to be effective. Here is a way I like

@Bean
FilterRegistrationBean<ExceptionHandlerFilter> exceptionFilterRegistrationBean() {
    FilterRegistrationBean<ExceptionHandlerFilter> bean = new FilterRegistrationBean<>();
    (new ExceptionHandlerFilter());
    (Ordered.HIGHEST_PRECEDENCE);//Put it in the front    return bean;
}

Unknown exception handling

When the exception that occurs is unknown, springboot will perform the default exception processing and jump to /error

At this time, if we want to unify the data return, we must start from this, create a new controller to process/error, and inherit itBasicErrorControllerand overwrite the method in it

@RestController
public class MyErrorController extends BasicErrorController {
    @Autowired
    public MyErrorController(ErrorAttributes errorAttributes,
                             ServerProperties serverProperties,
                             List<ErrorViewResolver> errorViewResolvers) {
        super(errorAttributes, (), errorViewResolvers);
    }
    @Override
    public ModelAndView errorHtml(HttpServletRequest request,
                                  HttpServletResponse response) {
        HttpStatus status = getStatus(request);
        Map<String, Object> model = Collections
                .unmodifiableMap(getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.TEXT_HTML)));
//        return new ModelAndView("error", model, status);
        (response, ().code(()).message((String) ("error")));
        return null;
    }
    @Override
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request, ));
        //It can be replaced with a custom communication json in the project        Map<String, Object> resultBody = new HashMap<>(16);
        ("success", false);
        ("code", ("status"));
        ("message", ("error"));
        Map<String, Object> data = new HashMap<>();
        ("timestamp", ("timestamp"));
        ("path", ("path"));
        ("data", data);
        return new ResponseEntity<>(resultBody, );
    }
}

Configuration File

spring:
  mvc:
    throw-exception-if-no-handler-found: true
  web:
    resources:
      add-mappings: false
server:
  error:
    include-exception: true
  servlet:
    encoding:
      charset: utf-8

Unified result returns tool class

ResponseUtils

public class ResponseUtils {
    public static void out(HttpServletResponse response, R r) {
        ObjectMapper mapper = new ObjectMapper();
        (());
        ("application/json;charset=UTF-8");
        try {
            ((), r);
        } catch (IOException e) {
            ();
        }
    }

R

@Data
public class R implements Serializable {
    private boolean success;
    private Integer code;
    private String message;
    private Map<String,Object> data;
    private R(){}
    public static R ok(){
        R r = new R();
        (true);
        (200);
        ("success");
        (new HashMap<>());
        return r;
    }
    public static R error() {
        R r = new R();
        (false);
        (500);
        ("fail");
        (new HashMap<>());
        return r;
    }
    public R success(Boolean success){
         = success;
        return this;
    }
    public R code(Integer code){
         = code;
        return this;
    }
    public R message(String message){
         = message;
        return this;
    }
    public R data(String key, Object value){
        (key,value);
        return this;
    }
    public R data(Map<String,Object> map){
        (map);
        return this;
    }
}

This is the article about springboot unified exception handling (return to json) and formatting exceptions. For more related springboot unified exception handling content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!