全局异常处理

package com.haylion.maastaxi.facade.exception;


import com.haylion.maastaxi.common.code.SysStubInfo;
import com.haylion.maastaxi.common.exception.ApplicationException;
import com.haylion.maastaxi.facade.view.JsonView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author fengjianshe 统一异常处理逻辑
 */
@ControllerAdvice
public class ExceptionHandle {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);
    private static final Map EMPTY_DATA = null;

    /**
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public JsonView exceptionGet(Exception e) {
        logger.error("Exception for handle ", e);
        JsonView<Map> jsonView;
        if (e instanceof ApplicationException) {
            jsonView = new JsonView<>();
            jsonView.setData(EMPTY_DATA);

            ApplicationException applicationException = (ApplicationException) e;
            jsonView.setCode(applicationException.getRetStub().getCode());
            jsonView.setMessage(applicationException.getRetStub().getMsg());

        } else if (e instanceof IllegalArgumentException) {
            jsonView = new JsonView<>();
            jsonView.setData(EMPTY_DATA);

            jsonView.setCode(SysStubInfo.PARAMETER_TYPE_INVALID.getCode());
            jsonView.setMessage(SysStubInfo.PARAMETER_TYPE_INVALID.getMsg());

        } else if (e instanceof ConstraintViolationException) {
            ConstraintViolationException applicationException = (ConstraintViolationException) e;
            Set<ConstraintViolation<?>> violations = applicationException.getConstraintViolations();
            StringBuilder stringBuilder = new StringBuilder();
            for (ConstraintViolation<?> item : violations) {
                stringBuilder.append("[").append(item.getMessage()).append("]");
            }
            String msg = stringBuilder.toString();
            logger.error("ConstraintViolation msg is : " + msg);
            jsonView = new JsonView<>(SysStubInfo.PARAMETER_TYPE_INVALID, msg, EMPTY_DATA);

        } else if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException applicationException = (MethodArgumentNotValidException) e;
            List<ObjectError> allErrors = applicationException.getBindingResult().getAllErrors();
            StringBuilder stringBuilder = new StringBuilder();
            for (ObjectError error : allErrors) {
                stringBuilder.append("[").append(error.getDefaultMessage()).append("]");
            }
            String msg = stringBuilder.toString();
            logger.error("ArgumentNotValid  msg is : " + msg);
            jsonView = new JsonView<>(SysStubInfo.PARAMETER_TYPE_INVALID, msg, EMPTY_DATA);

        } else if (e instanceof MissingServletRequestParameterException) {
            MissingServletRequestParameterException applicationException = (MissingServletRequestParameterException) e;
            String parameterName = applicationException.getParameterName();
            String parameterType = applicationException.getParameterType();
            String msg = ("parameter " + parameterName + " is null " + " , expect: " + parameterType);
            jsonView = new JsonView<>(SysStubInfo.PARAMETER_IS_NULL, msg, EMPTY_DATA);

        } else if (e instanceof HttpMediaTypeNotSupportedException) {
            HttpMediaTypeNotSupportedException applicationException = (HttpMediaTypeNotSupportedException) e;
            String msg = applicationException.getContentType().getSubtype();
            jsonView = new JsonView<>(SysStubInfo.CONTENT_TYPE_INVALID, msg, EMPTY_DATA);

        } else if (e instanceof HttpRequestMethodNotSupportedException) {
            HttpRequestMethodNotSupportedException applicationException = (HttpRequestMethodNotSupportedException) e;
            String msg = applicationException.getMethod();
            jsonView = new JsonView<>(SysStubInfo.METHOD_INVALID, msg, EMPTY_DATA);

        } else if (e instanceof NoHandlerFoundException) {
            NoHandlerFoundException applicationException = (NoHandlerFoundException) e;
            String msg = (applicationException.getHttpMethod() + " --> " + applicationException.getRequestURL());
            jsonView = new JsonView<>(SysStubInfo.RESOURCE_INVALID, msg, EMPTY_DATA);

        } else if (e instanceof MethodArgumentTypeMismatchException) {
            MethodArgumentTypeMismatchException applicationException = (MethodArgumentTypeMismatchException) e;
            String msg = ("parameter " + applicationException.getName() + " is not type of " + applicationException
                    .getRequiredType().getSimpleName());
            jsonView = new JsonView<>(SysStubInfo.PARAMETER_TYPE_INVALID, msg, EMPTY_DATA);

        } else if (e instanceof HttpMessageNotReadableException) {
            HttpMessageNotReadableException applicationException = (HttpMessageNotReadableException) e;
            String msg = applicationException.getMessage();
            jsonView = new JsonView<>(SysStubInfo.REQUEST_BODY_INVALID, msg, EMPTY_DATA);

        } else if (e instanceof BindException) {
            BindException applicationException = (BindException) e;
            BindingResult bindingResult = applicationException.getBindingResult();
            FieldError fieldError = bindingResult.getFieldError();
            String field = fieldError.getField();
            jsonView = new JsonView<>(SysStubInfo.PARAMETER_IS_NULL, field, EMPTY_DATA);

        } else {
            jsonView = new JsonView<>(SysStubInfo.DEFAULT_FAIL, EMPTY_DATA);
        }
        return jsonView;
    }

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值