spring 统一异常处理

原创
2019/09/03 14:49
阅读数 270

异常处理的方法有很多,比如自定义一个ServiceException,在service层或者是controller层调用,本文主要是将通过spring统一处理所有接收到的异常,生成前台能够处理(比如json格式的异常),或者是用户能够看懂(比如nullexception,普通用户很难看懂什么意思)。

下面请看代码,代码只是举几个常见的异常,大家生产情况下会有很多异常出现,需要大家不断扩充这个统一异常处理类。

 

import java.util.Iterator;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.rpc.RpcException;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


import cn.he.tips.ErrorTip;

/**
 * 异常处理器
 *
 */
@RestControllerAdvice
public class ServiceExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(ServiceException.class)
    public ErrorTip handleException(ServiceException e){
        ErrorTip tip = new ErrorTip(0,e.getMessage());
        
        return tip;
    }

    
    @ExceptionHandler(AuthorizationException.class)
    public ErrorTip handleException(AuthorizationException e){
        if(logger.isDebugEnabled())
            logger.error(e.getMessage(), e);
        ErrorTip tip = new ErrorTip(0,"没有权限,请联系管理员授权");
        
        return tip;
    }

    
    @ExceptionHandler(java.lang.NumberFormatException.class)
    public ErrorTip handleException(NumberFormatException e){
        if(logger.isDebugEnabled())
            logger.error(e.getMessage(), e);
        ErrorTip tip = new ErrorTip(0,"数字类型转换错误");
        return tip;
    }
    
    
    
    
    @ExceptionHandler(org.springframework.http.converter.HttpMessageNotReadableException.class)
    public ErrorTip handleException(org.springframework.http.converter.HttpMessageNotReadableException e){
        if(logger.isDebugEnabled())
            logger.error(e.getMessage(), e);
        ErrorTip tip = new ErrorTip(0,"Bad Request!");
        return tip;
    }
    
    
    
    @ExceptionHandler(RemotingException.class)
    public ErrorTip handleException(RemotingException e){
        ErrorTip tip = null;
        if(logger.isDebugEnabled()) {
            logger.error(e.getMessage(), e);
            tip = new ErrorTip(0,"Dubbo远程服务停止");
        }else {
            tip = new ErrorTip(0,"微服务停止服务");
        }
            
        return tip;
    }
    
    
    
    
    @ExceptionHandler(java.io.NotSerializableException.class)
    public ErrorTip handleException(java.io.NotSerializableException e){
        ErrorTip tip = null;
        if(logger.isDebugEnabled()) {
            logger.error(e.getMessage(), e);
            tip = new ErrorTip(0,"类未序列化:"+e.getCause().getMessage());
        }else {
            tip = new ErrorTip(0,"实体类未序列化");
        }
        
        return tip;
    }
    
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ErrorTip handleException(MethodArgumentNotValidException e){
        ErrorTip tip = null;
        if(logger.isDebugEnabled()) {
            logger.error(e.getMessage(), e);
            tip = new ErrorTip(0,"方法参数验证错误:"+e.getCause().getMessage());
        }else {
            tip = new ErrorTip(0,"方法参数验证错误");
        }
        
        return tip;
    }
    
    @ExceptionHandler(java.lang.NullPointerException.class)
    public ErrorTip handleException(NullPointerException e){
        ErrorTip tip = null;
        if(logger.isDebugEnabled()) {
            logger.error(e.getMessage(), e);
            tip = new ErrorTip(0,"空指针错误:"+e.getCause().getMessage());
        }else {
            tip = new ErrorTip(0,"空指针错误");
        }
        
        return tip;
    }
   

    //==============
    //----验证异常
    //==============
    
    @ExceptionHandler(RpcException.class)
    public ErrorTip handleException(RpcException e){
        if(logger.isDebugEnabled())
            logger.error(e.getMessage(), e);
        String error = "";
        if(e.getCause() instanceof ConstraintViolationException){
            ConstraintViolationException ve = (ConstraintViolationException)e.getCause();
            if(ve != null){
                Set<ConstraintViolation<?>> violations = ve.getConstraintViolations();
                Iterator<ConstraintViolation<?>> it = violations.iterator();  
                while (it.hasNext()) {  
                    ConstraintViolation str = it.next();  
                    error += str.getMessage()+"<br>";
                }  
            }
        }else if(e.getCause() instanceof ServiceException){
            error += e.getMessage();
        }else{
            error += e.getCause().getLocalizedMessage();
        }
        
        if(StringUtils.isEmpty(error)) {
            error = "RCP远程调用失败!";
        }
        ErrorTip tip = new ErrorTip(0,error);
        return tip;
    }
    
    @ExceptionHandler(ValidationException.class)
    public ErrorTip handleException(ValidationException e){
        if(logger.isDebugEnabled())
            logger.error(e.getMessage(), e);
        ErrorTip tip = new ErrorTip(0,e.getMessage());
        return tip;
    }
    
    @ExceptionHandler(ConstraintViolationException.class)
    public ErrorTip handleException(ConstraintViolationException e){
        if(logger.isDebugEnabled())
            logger.error(e.getMessage(), e);
        ErrorTip tip = new ErrorTip(0,e.getMessage());
        return tip;
    }
    
    //==================
    //----JSON处理错误
    //==================
    
    @ExceptionHandler(ValidateException.class)
    public ErrorTip handleException(ValidateException e){
        if(logger.isDebugEnabled())
            logger.error("参数验证错误:"+e.getMessage(), e);
        ErrorTip tip = new ErrorTip(0,e.getMessage());
        return tip;
    }
    
    
    @ExceptionHandler(com.alibaba.fastjson.JSONException.class)
    public ErrorTip handleException(com.alibaba.fastjson.JSONException e){
        ErrorTip tip = null;
        if(logger.isDebugEnabled()) {
            logger.error(e.getMessage(), e);
            tip = new ErrorTip(0,"JSON数据转换类型错误:"+e.getCause().getMessage());
        }else {
            tip = new ErrorTip(0,"JSON数据转换类型错误");
        }
        
        return tip;
    }
    
    @ExceptionHandler(com.fasterxml.jackson.databind.exc.InvalidFormatException.class)
    public ErrorTip handleException(com.fasterxml.jackson.databind.exc.InvalidFormatException e){
        ErrorTip tip = null;
        if(logger.isDebugEnabled()) {
            logger.error(e.getMessage(), e);
            tip = new ErrorTip(0,"JSON数据转换类型错误:"+e.getCause().getMessage());
        }else {
            tip = new ErrorTip(0,"JSON数据转换类型错误");
        }
        return tip;
    }
    
    
    //=========================
    //---数据库操作失败
    //=========================
    @ExceptionHandler(DuplicateKeyException.class)
    public ErrorTip handleException(DuplicateKeyException e){
        ErrorTip tip = null;
        if(logger.isDebugEnabled()) {
            logger.error(e.getMessage(), e);
            tip = new ErrorTip(0,"数据库中已存在该记录:"+e.getCause().getMessage());
        }else {
            tip = new ErrorTip(0,"数据库中已存在该记录");
        }
        
        return tip;
    }


    @ExceptionHandler(DataNotExistException.class)
    public ErrorTip handleException(DataNotExistException e){
        ErrorTip tip = null;
        if(logger.isDebugEnabled()) {
            logger.error(e.getMessage(), e);
            tip = new ErrorTip(0,"要访问的数据不存在:"+e.getCause().getMessage());
        }else {
            tip = new ErrorTip(0,"要访问的数据不存在");
        }
        
        return tip;
    }
    
    
    @ExceptionHandler(org.springframework.dao.DataIntegrityViolationException.class)
    public ErrorTip handleException(org.springframework.dao.DataIntegrityViolationException e){
        ErrorTip tip = null;
        if(logger.isDebugEnabled()) {
            logger.error(e.getMessage(), e);
            tip = new ErrorTip(0,"数据库字段属性输入错误:"+e.getCause().getMessage());
        }else {
            tip = new ErrorTip(0,"数据库字段属性输入错误");
        }
        
        return tip;
    }
    
    @ExceptionHandler(org.hibernate.hql.internal.ast.QuerySyntaxException.class)
    public ErrorTip handleException(org.hibernate.hql.internal.ast.QuerySyntaxException e){
        ErrorTip tip = null;
        if(logger.isDebugEnabled()) {
            logger.error(e.getMessage(), e);
            tip = new ErrorTip(0,"Hibernate操作数据库操作错误:"+e.getMessage());
        }else {
            tip = new ErrorTip(0,"Hibernate操作数据库操作错误");
        }
        
        return tip;
    }
    
    @ExceptionHandler(org.hibernate.exception.SQLGrammarException.class)
    public ErrorTip handleException(org.hibernate.exception.SQLGrammarException e){
        ErrorTip tip = null;
        if(logger.isDebugEnabled()) {
            logger.error(e.getMessage(), e);
            tip = new ErrorTip(0,"Hibernate异常:SQL参数不一致。"+e.getMessage());
        }else {
            tip = new ErrorTip(0,"Hibernate异常:SQL参数不一致。");
        }
        
        return tip;
    }
    
    @ExceptionHandler(org.hibernate.StaleStateException.class)
    public ErrorTip handleException(org.hibernate.StaleStateException e){
        ErrorTip tip = null;
        if(logger.isDebugEnabled()) {
            logger.error(e.getMessage(), e);
            tip = new ErrorTip(0,"Hibernate操作数据库错误:"+e.getMessage());
        }else {
            tip = new ErrorTip(0,"Hibernate操作数据库错误。");
        }
        
        
        return tip;
    }
    
    @ExceptionHandler(org.springframework.orm.hibernate5.HibernateOptimisticLockingFailureException.class)
    public ErrorTip handleException(org.springframework.orm.hibernate5.HibernateOptimisticLockingFailureException e){
        ErrorTip tip = null;
        if(logger.isDebugEnabled()) {
            logger.error(e.getMessage(), e);
            tip = new ErrorTip(0,"Hibernate操作数据库错误:"+e.getMessage());
        }else {
            tip = new ErrorTip(0,"Hibernate操作数据库错误。");
        }
        
        return tip;
    }
    
    
    @ExceptionHandler(org.mybatis.spring.MyBatisSystemException.class)
    public ErrorTip handleException(org.mybatis.spring.MyBatisSystemException e){
        ErrorTip tip = null;
        if(logger.isDebugEnabled()) {
            logger.error(e.getMessage(), e);
            tip = new ErrorTip(0,"Mybatis操作数据库操作错误:"+e.getMessage());
        }else {
            tip = new ErrorTip(0,"Mybatis操作数据库操作错误。");
        }
        
        return tip;
    }
    @ExceptionHandler(org.apache.ibatis.binding.BindingException.class)
    public ErrorTip handleException(org.apache.ibatis.binding.BindingException e){
        ErrorTip tip = null;
        if(logger.isDebugEnabled()) {
            logger.error(e.getMessage(), e);
            tip = new ErrorTip(0,"Mybatis方法或参数绑定错误:"+e.getMessage());
        }else {
            tip = new ErrorTip(0,"Mybatis方法或参数绑定错误。");
        }
        return tip;
    }
    
    
    @ExceptionHandler(org.springframework.dao.InvalidDataAccessResourceUsageException.class)
    public ErrorTip handleException(org.springframework.dao.InvalidDataAccessResourceUsageException e){
        ErrorTip tip = null;
        if(logger.isDebugEnabled()) {
            logger.error(e.getMessage(), e);
            tip = new ErrorTip(0,"DAO数据库操作失败:"+e.getMessage());
        }else {
            tip = new ErrorTip(0,"DAO数据库操作失败。");
        }
        
        return tip;
    }
    
    @ExceptionHandler(org.apache.dubbo.remoting.TimeoutException.class)
    public ErrorTip handleException(org.apache.dubbo.remoting.TimeoutException e){
        ErrorTip tip = null;
        if(logger.isDebugEnabled()) {
            logger.error(e.getMessage(), e);
            tip = new ErrorTip(0,"DUBBO远程调用超时,请联系系统管理员调整超时时间。");
        }else {
            tip = new ErrorTip(0,"DUBBO远程调用超时,请联系系统管理员调整超时时间。");
        }
        
        return tip;
    }
   
    @ExceptionHandler(org.elasticsearch.action.ActionRequestValidationException.class)
    public ErrorTip handleException(org.elasticsearch.action.ActionRequestValidationException e){
        ErrorTip tip = null;
        if(logger.isDebugEnabled()) {
            logger.error(e.getMessage(), e);
            tip = new ErrorTip(0,"ElasticSearch错误信息:"+e.getMessage());
        }else {
            tip = new ErrorTip(0,"ElasticSearch错误信息。");
        }
        
        return tip;
    }
    
    
    @ExceptionHandler(Exception.class)
    public ErrorTip handleException(Exception e){
        ErrorTip tip = null;
        if(logger.isDebugEnabled()) {
            logger.error(e.getMessage(), e);
            tip = new ErrorTip(0,"未知错误:"+e.getMessage());
        }else {
            tip = new ErrorTip(0,"未知错误:"+e.getMessage());
        }
        return tip;
    }
    
}

 

 

public class ErrorTip {

    private int code;
    private String message;

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

    public int getCode() {
        return code;
    }

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

    public String getMessage() {
        return message;
    }

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

   
}

 

代码里面有些异常大家用不到的可以删掉,去建立、丰富你自己的异常处理类,希望能对大家有帮助

展开阅读全文
加载中

作者的其它热门文章

打赏
0
0 收藏
分享
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部