【自定义全局异常处理类】

自定义全局异常处理类

  • 前言
  • 直接上步骤
    • 1.创建一个结果封装类
    • 2.创建一个全局异常处理类
    • 3.开发异常处理器ExceptionHandle
    • 4.测试
  • 总结


前言

有时候我们需要在项目中写一个全局异常类,来处理我们项目中可能出现的异常信息,并返回给前端相关信息进行处理


直接上步骤

1.创建一个结果封装类

创建一个结果封装类,用于异常信息的装入,并返回给前端相关信息

package com.example.mybatisplus.exception;

import com.example.mybatisplus.util.JsonUtil;
import com.fasterxml.jackson.databind.JavaType;


import java.io.Serializable;
import java.util.List;



/**
 * @author xbxqc
 */
public class Result<T> implements Serializable {

	private static final long serialVersionUID = 1L;
	//"业务调用是否成功"
	private boolean success;
	// 是否由dataList装载业务数据
	private boolean wrapList = false;
	// "错误编码"
	private int code;
    //"错误信息"
	private String msg;
	// 当返回的数据为单对象是实用此属性
	private T data;
	// 当返回的数据为list实用此属性
	private List<T> dataList;

	public static <T> Result<T> getResultFromJson(String json, Class<T> dataClass) {

		JavaType javaType = JsonUtil.getMapper().getTypeFactory().constructParametricType(Result.class, dataClass);
		try {
			return JsonUtil.getMapper().readValue(json, javaType);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public Result() {
		this.success = true;
	}

	public Result(boolean success) {
		this.success = success;
	}

	public Result(boolean success, boolean wrapList) {
		this.success = success;
		this.wrapList = wrapList;
	}

	public Result(String msg, boolean success) {
		this.msg = msg;
		this.success = success;
	}

	public Result(String msg, boolean success, boolean wrapList) {
		this.msg = msg;
		this.success = success;
		this.wrapList = wrapList;
	}

	public int getCode() {
		return code;
	}

	public void setCode(int code) {
		this.code = code;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public Result(T data) {
		this.data = data;
	}

	public Result(boolean success, T data) {
		this.success = success;
		this.data = data;
	}

	/**
	 * @return the success
	 */
	public boolean isSuccess() {
		return success;
	}

	/**
	 * @param success the success to set
	 */
	public void setSuccess(boolean success) {
		this.success = success;
	}

	/**
	 * @return the data
	 */
	public Object getData() {
		return data;
	}

	/**
	 * @param data the data to set
	 */
	public void setData(T data) {
		if (wrapList) {
			throw new RuntimeException("Please use setDataList because of wrapList:" + wrapList);
		}
		this.data = data;
	}

	/**
	 * @return the datum
	 */
	public List<T> getDataList() {
		return dataList;
	}

	/**
	 * @param datum the datum to set
	 */
	public void setDataList(List<T> dataList) {
		if (wrapList || dataList == null) {
			this.dataList = dataList;
		} else {
			throw new RuntimeException("Please use setData because of wrapList:" + wrapList);
		}
	}

	/**
	 * @return the wrapList
	 */
	public boolean isWrapList() {
		return wrapList;
	}

	/**
	 * @param wrapList the wrapList to set
	 */
	public void setWrapList(boolean wrapList) {
		this.wrapList = wrapList;
	}

	@Override
	public String toString() {
		return "Result [success=" + success + ", code=" + code + ", msg=" + msg + ", data=" + data + "]";
	}

}

2.创建一个全局异常处理类

创建一个全局自定义异常类 继承 RuntimeException

package com.example.mybatisplus.exception;

import lombok.Data;
import lombok.EqualsAndHashCode;


/**
 * @author xbxqc
 */
@Data
@EqualsAndHashCode(callSuper = true)
public class BusinessException extends RuntimeException {
	private static final long serialVersionUID = 1L;
	private String message;
	private int code = -1;

	public BusinessException() {

	}

	public BusinessException(String message) {
		this.message = message;
	}

	public BusinessException(String message, int code) {
		this.message = message;
		this.code = code;
	}

}

3.开发异常处理器ExceptionHandle

@ControllerAdvice
这是一个增强的 Controller。使用这个 Controller ,可以实现三个方面的功能:

1.全局异常处理;

2.全局数据绑定

3.全局数据预处理

@ExceptionHandler
注解我们一般是用来自定义异常的。
可以认为它是一个异常拦截器(处理器)。
@ExceptionHandler里面参数加入我们自定义的异常类
具体用法的化百度一下

package com.example.mybatisplus.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author xbxqc
 */
@Slf4j
@ControllerAdvice
public class ResultExceptionHandler {
    @ResponseBody
    @ExceptionHandler(BusinessException.class)
    public Result<String> resultExceptionHandler(BusinessException e) {
        log.error("Exception:", e);
        Result<String> result = new Result<String>();
        result.setCode(e.getCode());
        result.setSuccess(false);
        result.setMsg(e.getMessage());
        return result;
    }
}

4.测试

package com.example.mybatisplus.controller;

import com.example.mybatisplus.config.User;
import com.example.mybatisplus.exception.BusinessException;
import com.example.mybatisplus.exception.Result;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author xbxqc
 */
@RestController
@RequestMapping("testController")
public class TestController {
    @GetMapping("test2")
    public Result<String> getBusinessException(int a){
        if (a==1){
            throw new BusinessException("操作失败",-1);
        }
        Result<String> result = new Result<>();
        result.setMsg("操作成功");
        result.setData("成功");
        result.setCode(200);
        return  result;
    }
}

【自定义全局异常处理类】_第1张图片
如果你的返回值不是自定义的信息而是一串报错信息请在配置文件里面加入这两个配置

#自定义异常处理页面,异常对象。异常信息
server.error.include-exception=true
server.error.include-message=always

总结

以上就是我实操的关系自定义的全局异常信息,全局异常处理信息可以方便我们找出一些可以预期的异常,还是比较便捷!

你可能感兴趣的:(java功能,java,mybatis,数据库)