custom global exception

1. When the interface returns json data, there should be return formats and fields in the system. First, define the unified fields when json returns.

① It is recommended to use lombok's @Getter and @Setter annotations in the idea. After using this annotation, you don't need to write the get/set method, it will be automatically generated to avoid frequent modification of the method after modifying the field and reducing the efficiency of the opening method

②Sometimes the returned json data does not contain data, or the data is NULL, this field is not necessary, in this case, we can use class annotation

@JsonInclude(Include.NON_NULL)

To exclude NULL fields, so that the returned data does not contain NULL fields

package com.hz1202.common;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

@Getter
@JsonInclude(Include.NON_NULL)
public class JsonData<T> implements Serializable {

    private int status;
    private String msg;
    private T data;

    private JsonData(int status) {
        this.status = status;
    }

    private JsonData(String msg) {
        this.msg = msg;
    }

    private JsonData(T data) {
        this.data = data;
    }

    private JsonData(int status, String msg) {
        this.status = status;
        this.msg = msg;
    }

    private JsonData(int status, T data) {
        this.status = status;
        this.data = data;
    }

    private JsonData(int status, String msg, T data) {
        this.status = status;
        this.msg = msg;
        this.data = data;
    }

    //使之不在json返回结果当中
    @JsonIgnore
    public boolean isSuccess() {
        return this.status == 1;
    }

    public static JsonData createSuccess() {
        return new JsonData(1);
    }

    public static JsonData createSuccess(String msg) {
        return new JsonData(1, msg);
    }

    public static <T> JsonData<T> createSuccess(T data) {
        return new JsonData(1, data);
    }

    public static <T> JsonData<T> createSuccess(String msg, T data) {
        return new JsonData(1, msg, data);
    }

    public static JsonData createError() {
        return new JsonData(1);
    }

    public static JsonData createError(String msg) {
        return new JsonData(0, msg);
    }

    public static JsonData createError(int status, String msg) {
        return new JsonData(status, msg);
    }

    public Map<String, Object> toMap() {
        HashMap<String, Object> result = new HashMap<String, Object>();
        result.put("status", status);
        result.put("msg", msg);
        if(data != null){
            result.put("data", data);
        }
        return result;
    }
}

2. Define our own custom exception. Custom exceptions need to inherit RunTimeException and override the following methods. The shortcut key for the idea override method is "ctrl+o"

package com.hz1202.exception;

public class PermissionException extends RuntimeException{
    public PermissionException() {
        super();
    }

    public PermissionException(String message) {
        super(message);
    }

    public PermissionException(String message, Throwable cause) {
        super(message, cause);
    }

    public PermissionException(Throwable cause) {
        super(cause);
    }

    protected PermissionException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

3. Customize the global exception class

1. Implement the HandlerExceptionResolver interface

② "jsonView" in the code is the id of the bean configured to process json in the spring-mvc configuration file spring-mvc.xml

package com.hz1202.common;

import com.hz1202.exception.PermissionException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class SpringExceptionResolver implements HandlerExceptionResolver{
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
        String url = request.getRequestURL().toString();
        ModelAndView mv;
        String defaultMsg = "System error";
        //定义文本请求和页面请求
        //json请求
        if(url.endsWith(".json")){
           //判断是否是我们自定义的异常
            if(e instanceof PermissionException){
                //创建异常返回信息
                JsonData jsonData = JsonData.createError(e.getMessage());
                //封装异常信息
                mv = new ModelAndView("jsonView",jsonData.toMap());
            }else{
                log.error("unkwon json exception={},url={},",e,url);
                JsonData jsonData = JsonData.createError(defaultMsg);
                mv = new ModelAndView("jsonView",jsonData.toMap());
            }
        }else if(url.endsWith(".page")){
            //页面请求
            log.error("unkwon page exception={},url={},",e,url);
            JsonData jsonData = JsonData.createError(defaultMsg);
            mv = new ModelAndView("exception",jsonData.toMap());
        }else{
            log.error("unkwon exception={},url={},",e,url);
            JsonData jsonData = JsonData.createError(defaultMsg);
            mv = new ModelAndView("jsonView",jsonData.toMap());
        }
        return mv;
    }
}

3. Configure global exception handling in spring-mvc.xml

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327065727&siteId=291194637