Java custom exception class handles exception uniformly

When the program is abnormal, it will return a lot of unfriendly content, which is very beautiful!

When we write code, exception handling is usually try catch or throws Exception.

As we all know, try catch takes up a lot of memory in the code and affects performance, and it is very tedious to add try catch to the code block of each method; throws Exception also needs to be added after each method.

So how to deal with exceptions in a unified way?

First, we create a class class class that inherits Exception or its subclasses:

/**
 * Custom exception class
 */
public class GlobalExecption extends RuntimeException {

    private static final long serialVersionUID = 4453214753962022203L;
    private Integer code;
    private String msg;

    public GlobalExecption() {}

    public GlobalExecption(int code, String msg) {
        super(msg);
        this.code = code;
        this.msg = msg;
    }

    public GlobalExecption(String msg) {
        super(msg);
        this.msg = msg;
    }

    public GlobalExecption(String msg, Throwable cause) {
        super(msg, cause);
        this.msg = msg;
    }

    public GlobalExecption(Integer code, String msg, Throwable cause) {
        super(msg, cause);
        this.code = code;
        this.msg = msg;
    }

    public static GlobalExecption paramException(String message) {
        GlobalExecption baseExecption = new GlobalExecption(HttpCode.CODE_400, message);
        return baseExecption;
    }

    public static GlobalExecption serverErrException(String message) {
        return new GlobalExecption(HttpCode.CODE_500, message);
    }

    public static GlobalExecption serverErrException(String message, Exception e) {
        return new GlobalExecption(HttpCode.CODE_500, message, e);
    }

    public Integer getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }
}

2. Create a Handler (very critical, where you can return the custom message body to the front-end page):

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

/**
 * Unified exception handling
 */
@RestControllerAdvice
public class DefaultExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(DefaultExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    public Result serverError(Exception e) {
        String errMsg = "";
        if (e instanceof NullPointerException) {
            errMsg = "Null pointer exception occurred";
        } else if (e instanceof RuntimeException) {
            errMsg = "Runtime exception occurred";
        } else {
            errMsg = "Unknown anomaly occurs";
        }
        logger.error("############" + errMsg + "############", e);
        return ResultTemplate.error(HttpCode.CODE_500, errMsg);
    }

    @ExceptionHandler(value = GlobalExecption.class)
    public Result<Object> paramError(GlobalExecption e) {
        logger.info("############" + e.getMsg() + "############");
        return ResultTemplate.error(e.getCode(), e.getMsg());
    }
}

Then post my ResultTemplate code:

import java.io.Serializable;

/**
 * Custom Return Page Result
 */
public class ResultTemplate<T> implements Serializable {

    private static final long serialVersionUID = -669633312320552296L;

    /**
     * Returns success for add, edit, delete operations
     * @param msg
     * @return
     */
    public static <T> Result<T> success(String msg) {
        Result <T>  result = new Result<T>();
        result.setSuccess(true);
        result.setCode(HttpCode.CODE_200);
        result.setMessage(msg);
        return result;
    }

    /**
     * Return success for query
     * @param data
     * @param msg
     * @param <T>
     * @return
     */
    public static <T> Result<T> successData(T data, String msg) {
        Result result = new Result<>();
        result.setSuccess(true);
        result.setCode(HttpCode.CODE_200);
        result.setMessage(msg);
        result.setData(data);
        return result;
    }


    /**
     * Returns success for add, edit, delete operations
     * @param msg
     * @return
     */
    public static <T> Result<T> fail(String msg) {
        Result <T>  result = new Result<T>();
        result.setSuccess(false);
        result.setCode(HttpCode.CODE_500);
        result.setMessage(msg);
        return result;
    }

    public static <T> Result<T> error(Integer code, String msg) {
        Result <T>  result = new Result<T>();
        result.setSuccess(false);
        result.setCode(code);
        result.setMessage(msg);
        return result;
    }
}

Here we must not use e.printStackTrace(); to print exceptions to the console (e.printStackTrace() to generate error stack strings into the string pool memory space, when the memory space is full, resulting in service application downtime.

3. Next, we throw a custom exception in our code:

@PostMapping("/queryAll")
@LogByMethod(remark = "Query everyone", editType = EditTypeEnum.QUERY)
public Result queryAll(@RequestBody Map<String, String> map) {
    if (true) {
        throw GlobalExecption.serverErrException("Test exception handling");
    }
    threadService.queryAll();
    return ResultTemplate.success(ComMsgContent.QUERY_SUCCESS_MSG);
}

What results are returned under the postman call test?

Then look at the console output:

ok, here we have completed the unified handling of custom exceptions!

Keywords: Java

Added by foochuck on Sat, 05 Oct 2019 20:55:04 +0300