Springboot项目自定义异常全局处理实践

        还是常规的原因,日常开发中的小细节记录,本次主要是简单描述一下在spring下对于全局异常的处理方案,网上也有各种各样的方案,有很优雅的,也有很直接的。

        我本次项目的框架体系大致就是springboot的一套直接贴代码:

package com.utils;

import com.sun.corba.se.impl.io.TypeMismatchException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @title: 全局异常处理
 * @author yanwei.shen
 * @projectName zeus-service
 * @description: TODO
 * @date 2019/11/2018:56
 */
@ControllerAdvice
public class ZeusExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(ZeusExceptionHandler.class);


    //空指针的异常
    @ExceptionHandler(NullPointerException.class)
    public Result exceptionHandler(HttpServletRequest req, NullPointerException e){
        logger.error("发生空指针异常!原因是:",e);
        return ResultUtil.error(e.getMessage());
    }
    //运行时异常
    @ExceptionHandler(RuntimeException.class)
    public Result runtimeExceptionHandler(RuntimeException e) {
        logger.error("运行时异常 !原因是:",e);
        return ResultUtil.error(e.getMessage());
    }
    //类型转换异常
    @ExceptionHandler(ClassCastException.class)
    public Result classCastExceptionHandler(ClassCastException e) {
        logger.error("类型转换异常 !原因是:",e);
        return ResultUtil.error(e.getMessage());
    }

    //IO异常
    @ExceptionHandler(IOException.class)
    public Result iOExceptionHandler(IOException e) {
        logger.error("IO异常 !原因是:",e);
        return ResultUtil.error(e.getMessage());
    }

    //未知方法异常
    @ExceptionHandler(NoSuchMethodException.class)
    public Result noSuchMethodExceptionHandler(NoSuchMethodException e) {
        logger.error("未知方法异常 !原因是:",e);
        return ResultUtil.error(e.getMessage());
    }

    //数组越界异常
    @ExceptionHandler(IndexOutOfBoundsException.class)
    public Result indexOutOfBoundsExceptionHandler(IndexOutOfBoundsException e) {
        logger.error("数组越界异常 !原因是:",e);
        return ResultUtil.error(e.getMessage());
    }

    //400错误
    @ExceptionHandler({HttpMessageNotReadableException.class})
    public Result requestNotReadable(HttpMessageNotReadableException e) {
        logger.error("400异常 !原因是:",e);
        return ResultUtil.error(e.getMessage());
    }

    //400错误
    @ExceptionHandler({TypeMismatchException.class})
    public Result requestTypeMismatch(TypeMismatchException e) {
        logger.error("400异常 !原因是:",e);
        return ResultUtil.error(e.getMessage());
    }

    //400错误
    @ExceptionHandler({MissingServletRequestParameterException.class})
    public Result requestMissingServletRequest(MissingServletRequestParameterException e) {
        logger.error("400异常 !原因是:",e);
        return ResultUtil.error(e.getMessage());
    }

    //405错误
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public Result request405(HttpRequestMethodNotSupportedException e) {
        logger.error("405异常 !原因是:",e);
        return ResultUtil.error(e.getMessage());
    }

    //406错误
    @ExceptionHandler({HttpMediaTypeNotAcceptableException.class})
    public Result request406(HttpMediaTypeNotAcceptableException e) {
        logger.error("406异常 !原因是:",e);
        return ResultUtil.error(e.getMessage());
    }

    //500错误
    @ExceptionHandler({ConversionNotSupportedException.class, HttpMessageNotWritableException.class})
    public Result server500(RuntimeException e) {
        logger.error("500异常 !原因是:",e);
        return ResultUtil.error(e.getMessage());
    }

    //栈溢出
    @ExceptionHandler({StackOverflowError.class})
    public Result requestStackOverflow(StackOverflowError e) {
        logger.error("栈溢出异常 !原因是:",e);
        return ResultUtil.error(e.getMessage());
    }

    //其他错误
    @ExceptionHandler({Exception.class})
    public Result exception(Exception e) {
        logger.error("其他异常 !原因是:",e);
        return ResultUtil.error(e.getMessage());
    }
}
package com.utils;

/**
 * 返回页面统一格式化工具类
 * @title: ResultUtil
 * @author yanwei.shen
 * @projectName zeus-service
 * @description: TODO
 * @date 2019/11/2018:44
 */
public class ResultUtil {
    public static Result success(Object object) {
        Result result = new Result();
        result.setCode(200);
        result.setMessage("成功");
        result.setData(object);
        return result;
    }

    public static Result success() {
        return success(null);
    }

    public static Result error( String msg) {
        Result result = new Result();
        result.setCode(404);
        result.setMessage(msg);
        return result;
    }

    public static Result error403 (){
        Result result = new Result();
        result.setCode(403);
        result.setMessage("no session");
        return result;
    }

}
package com.utils;

import java.io.Serializable;

/**
 * 请求返回前端页面统一格式类
 * @title: Result
 * @author yanwei.shen
 * @projectName zeus-service
 * @description: TODO
 * @date 2019/11/2018:41
 */
public class Result  implements Serializable {

    private static final long serialVersionUID = -6839511962858256723L;
    /** 错误码. */
    private Integer code;

    /** 提示信息. */
    private String message;

    /** 具体的内容. */
    private T data;

    public Integer getCode() {
        return code;
    }

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

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

总的结构就是三块,第一块异常处理,第二第三主要是统一返回格式

最关键的点就是@ControllerAdvice注解和@ExceptionHandler注解

简单的全局异常处理这样也还OK,如果有一些复杂的错误码,比如交易等系统,每个错误码有各自的意义,主要是还多 ,这种可以拓展返回类 

希望这些思路能给有需要的同学提供参考,有问题也可相互探讨

 

你可能感兴趣的:(技术)