springboot统一异常拦截

git
https://github.com/haohongyaocom/bootdemo

package com.example.demo.exception;

/**
 * @author hongtao.hao
 * @date 2019/6/27
 */
public class BusinessException extends RuntimeException {

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

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

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

}

package com.example.demo.exception;


import com.example.demo.common.Msg;

/**
 * @author hongtao.hao
 * @date 2019/6/27
 */
public class ServiceException extends BusinessException {

    private Msg msg;

    private Object data;

    public ServiceException(Msg msg) {
        super(msg.getTip());
        this.msg = msg;
    }

    public ServiceException(Msg msg, Object data) {
        super(msg.getTip());
        this.msg = msg;
        this.data = data;
    }

    public ServiceException(Msg msg, Throwable cause) {
        super(msg.getTip(), cause);
    }

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

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

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

    public Msg getMsg() {
        return msg;
    }

    public Object getData() {
        return data;
    }
}

package com.example.demo.interceptor;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.core.MethodParameter;
import org.springframework.dao.DuplicateKeyException;
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.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.alibaba.fastjson.JSON;
import com.example.demo.common.Msg;
import com.example.demo.common.ReturnResult;
import com.example.demo.exception.ServiceException;

/**
 * 异常拦截处理器
 * 
 * @author hongtao.hao
 * @date 2019/6/27
 */
@RestControllerAdvice
public class RestExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 自定义异常
     */
    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public String handleServiceException(ServiceException e) {
        printLog(e);
        return JSON.toJSONString(ReturnResult.createErrorReturn(e.getMsg()));
    }

    /**
     * 参数校验
     */
    //TODO 怎么只返回注解上的value
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public String handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        printLog(e);
        return JSON.toJSONString(ReturnResult.createErrorReturn(Msg.ParameterError.getCode(), e.getMessage()));
    }

    @ExceptionHandler(DuplicateKeyException.class)
    @ResponseBody
    public String handleDuplicateKeyException(DuplicateKeyException e) {
        printLog(e);
        return JSON.toJSONString(ReturnResult.createErrorReturn(Msg.DuplicateKeyError));
    }

     //shiro 权限
//     @ExceptionHandler(AuthorizationException.class)
//     @ResponseBody
//     public ReturnResult handleAuthorizationException(AuthorizationException e){
//     logger.error(e.getMessage(), e);
//     return ReturnResult.createSuccessReturn();
//
//     }

    /**
     * 运行时异常
     * 
     * @param e
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public String runtimeExceptionHandler(RuntimeException e) {
        printLog(e);
        return JSON.toJSONString(new ReturnResult<>(Msg.RuntimeException));
    }

    /**
     * 空指针异常
     * 
     * @param e
     * @return
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public String nullPointerExceptionHandler(NullPointerException e) {
        printLog(e);
        return JSON.toJSONString(new ReturnResult<>(Msg.NullPointerException));
    }

    /**
     * 类型转换异常
     * 
     * @param e
     * @return
     */
    @ExceptionHandler(ClassCastException.class)
    @ResponseBody
    public String classCastExceptionHandler(ClassCastException e) {
        printLog(e);
        return JSON.toJSONString(new ReturnResult<>(Msg.ClassCastException));
    }

    /**
     * IO异常
     * 
     * @param e
     * @return
     */
    @ExceptionHandler(IOException.class)
    @ResponseBody
    public String iOExceptionHandler(IOException e) {
        printLog(e);
        return JSON.toJSONString(new ReturnResult<>(Msg.IoException));
    }

    /**
     * 未知方法异常
     * 
     * @param e
     * @return
     */
    @ExceptionHandler(NoSuchMethodException.class)
    @ResponseBody
    public String noSuchMethodExceptionHandler(NoSuchMethodException e) {
        printLog(e);
        return JSON.toJSONString(new ReturnResult<>(Msg.NoSuchMethodException));
    }

    /**
     * 数组越界异常
     * 
     * @param e
     * @return
     */
    @ExceptionHandler(IndexOutOfBoundsException.class)
    @ResponseBody
    public String indexOutOfBoundsExceptionHandler(IndexOutOfBoundsException e) {
        printLog(e);
        return JSON.toJSONString(new ReturnResult<>(Msg.IndexOutOfBoundsException));
    }

    /**
     * 400错误
     * 
     * @param e
     * @return
     */
    @ExceptionHandler({HttpMessageNotReadableException.class})
    @ResponseBody
    public String requestNotReadable(HttpMessageNotReadableException e) {
        printLog(e);
        return JSON.toJSONString(new ReturnResult<>(Msg.RequestNotReadable));
    }

    /**
     * 400错误
     * 
     * @param e
     * @return
     */
    @ExceptionHandler({TypeMismatchException.class})
    @ResponseBody
    public String requestTypeMismatch(TypeMismatchException e) {
        printLog(e);
        return JSON.toJSONString(new ReturnResult<>(Msg.BadRequest));
    }

    /**
     * 400错误
     * 
     * @param e
     * @return
     */
    @ExceptionHandler({MissingServletRequestParameterException.class})
    @ResponseBody
    public String requestMissingServletRequest(MissingServletRequestParameterException e) {
        printLog(e);
        return JSON.toJSONString(new ReturnResult<>(Msg.BadRequest));
    }

    /**
     * 405错误
     * 
     * @return
     */
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    @ResponseBody
    public String request405() {
        return JSON.toJSONString(new ReturnResult<>(Msg.MethodNotAllowed));
    }

    /**
     * 406错误
     * 
     * @return
     */
    @ExceptionHandler({HttpMediaTypeNotAcceptableException.class})
    @ResponseBody
    public String request406() {
        return JSON.toJSONString(new ReturnResult<>(Msg.NotAcceptable));
    }

    /**
     * 500错误
     * 
     * @param e
     * @return
     */
    @ExceptionHandler({ConversionNotSupportedException.class, HttpMessageNotWritableException.class})
    @ResponseBody
    public String server500(RuntimeException e) {
        printLog(e);
        return JSON.toJSONString(new ReturnResult<>(Msg.Error));
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String handleException(Exception e) {
        printLog(e);
        return JSON.toJSONString(ReturnResult.createErrorReturn(Msg.Error));
    }

    /**
     * 异常信息打印日志
     *
     * @param e
     */
    private void printLog(Exception e) {

        logger.error("error >>> ", e);
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

orange大数据技术探索者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值