MySQLIntegrityConstraintViolationException 异常处理机制

package com.iflytek.exception;

import java.util.Map;

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

import com.iflytek.utils.ResultWrapper;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;

/**
 * 全局异常处理机制
 * @author zhangh
 * @date 2018年7月18日上午10:35:33
 */
@ControllerAdvice
public class MyExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyExceptionHandler.class);

    /**
     * 全局异常处理
     * 
     * @param e
     * @return 
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Map handle(Exception e) {
        return ResultWrapper.wrapErr(e.getMessage());
    }

    @ExceptionHandler(value = DuplicateKeyException.class)
    @ResponseBody
    public Map handleDuplicateKeyException(Exception e) {
        LOGGER.error("主键冲突:"+e.getMessage());
        return ResultWrapper.wrapErr("主键冲突:"+e.getMessage());
    }

    @ExceptionHandler(value = MySQLIntegrityConstraintViolationException.class)
    @ResponseBody
    public Map handleMySQLIntegrityConstraintViolationException(Exception e) {
        LOGGER.error("主键值重复:"+e.getMessage());
        return ResultWrapper.wrapErr("主键值重复:"+e.getMessage());
    }

    @ExceptionHandler(value = ArgumentsException.class)
    @ResponseBody
    public Map handleArgumentsException(Exception e) {
        LOGGER.error("参数异常:"+e.getMessage());
        return ResultWrapper.wrapErr("参数异常:"+e.getMessage());
    }

    @ExceptionHandler(value = ObjectNotExistException.class)
    @ResponseBody
    public Map handleObjectNotExistException(Exception e) {
        LOGGER.error("对象不存在:"+e.getMessage());
        return ResultWrapper.wrapErr("对象不存在:"+e.getMessage());
    }

    @ExceptionHandler(value = ReferencedException.class)
    @ResponseBody
    public Map handleReferencedException(Exception e) {
        LOGGER.error("对象引用异常:"+e.getMessage());
        return ResultWrapper.wrapErr("对象引用异常:"+e.getMessage());
    }

    @ExceptionHandler(value = SqlException.class)
    @ResponseBody
    public Map handleSqlException(Exception e) {
        LOGGER.error("SQL 异常:"+e.getMessage());
        return ResultWrapper.wrapErr("SQL 异常:"+e.getMessage());
    }
}

你可能感兴趣的:(mysql)