Getting started with SpringBoot 21, global exception handling

Posted by supanoob on Fri, 10 Jan 2020 16:17:58 +0100

There are two files in total. One deals with global exceptions, saves information to the log, and the other returns exception information to the interface. As long as its files are added to the project, no other configuration is needed

1. MyExceptionHandler.java global exception handling class

Priority is given to this class. It's not easy to grab 404, 403 and other error messages here
getMaps() please refer to Get the parameter information passed in the request
getHeaders() please refer to Get the header information passed in the request
The code is as follows:

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * <h5>Description: Global exception handling class < / H5 >
 * Execute this exception handling class first
 *  
 */
@ControllerAdvice
public class MyExceptionHandler {
    private final Logger log = LoggerFactory.getLogger(getClass());

    @ExceptionHandler(value =Exception.class)
    public String exceptionHandler(HttpServletRequest request, Exception e){
        Map<String, Object> paramsMap = getMaps(request);
        Map<String, Object> headersMap = getHeaders(request);

        String requestUri = request.getAttribute("org.springframework.web.servlet.HandlerMapping.lookupPath").toString();
        log.error("request[{}]Happen[{}]abnormal\r\n parameter[{}]\r\nheader[{}]", requestUri,e.getMessage(),paramsMap,headersMap, e);

        // Return error information to other exception handling classes
        return e.getMessage();
    }

    // =================== private method ===================

    /**
     * <h5>Function: get the parameter information passed from request < / H5 >
     * 
     * @return Map<String, Object>
     */
    private Map<String, Object> getMaps(HttpServletRequest request){
        Map<String, Object> paramMap = new HashMap<String, Object>();
        Enumeration<String> enume = request.getParameterNames();
        while (enume.hasMoreElements()) {
            String key = (String) enume.nextElement();
            String[] values = request.getParameterValues(key);
            paramMap.put(key, values.length == 1 ? request.getParameter(key).trim() : values);
        }

        return paramMap;
    }

    /**
     * <h5>Function: get the header information passed from the request < / H5 >
     * 
     * @return Map<String, Object>
     */
    private Map<String, Object> getHeaders(HttpServletRequest request) {
        Map<String, Object> headerMap = new HashMap<String, Object>();
        Enumeration<?> er = request.getHeaderNames();//Get all name values of the request header
        String headerName;
        while(er.hasMoreElements()){
            headerName = er.nextElement().toString();
            headerMap.put(headerName, request.getHeader(headerName));
        }

        return headerMap;
    }
}

2. MyErrorController.java global error information processing class

After executing this class, this class can effectively retrieve 404, 403 and other information. The code is as follows:

import javax.servlet.http.HttpServletRequest;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.jnxj.common.vo.MessageBean;

/**
 * <h5>Description: global error information processing < / H5 >
 *  Execute this class after executing exception handling class
 */
@RestController
public class MyErrorController implements ErrorController {

    @Override
    public String getErrorPath() {
        return "/error";
    }

    @RequestMapping("/error")
    public String handleError(HttpServletRequest request) {
        String message;
        // Get statuscode: 401404500
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == 400) {
            message = "Semantically incorrect,The current request cannot be understood by the server or the request parameters are wrong";
        } else if (statusCode == 401) {
            message = "Current request requires user authentication";
        } else if (statusCode == 403) {
            message = "Insufficient authority";
        } else if (statusCode == 404) {
            message = "The requested resource does not exist";
        } else {
            message = "The system got sick by accident,Emergency repair in progress,Please wait patiently...o(╥﹏╥)o";
        }

        MessageBean messageBean = new MessageBean();
        messageBean.setCode(statusCode.toString());
        messageBean.setMessage(message);
        return JSONObject.toJSONString(messageBean);
    }
}

Topics: Java