GlobalExceptionHandler.java 2.52 KB
package com.glsx.api.exception;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glsx.plat.common.utils.StringUtils;
import com.glsx.plat.core.web.R;
import com.netflix.hystrix.exception.HystrixRuntimeException;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * <p>Description:
 * <p>Project: chejia-smart
 *
 * @author wbh
 * @date 2021-03-16
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler({BusinessException.class})
    public R handleBusinessException(BusinessException e) {
        log.error("!!!! 业务异常", e);
        return R.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler({ServletRequestBindingException.class, MethodArgumentNotValidException.class,
            BindException.class})
    public R handleBindException(Exception e) {
        log.error("!!!! 参数错误", e);
        return R.error(ResultEnum.PARAM_ERROR.getCode(), ResultEnum.PARAM_ERROR.getMessage());
    }

    @ExceptionHandler({HystrixRuntimeException.class})
    public R handleHystrixException(HystrixRuntimeException e) {
        Throwable cause = e.getCause();
        if (cause instanceof FeignException) {
            FeignException feignException = (FeignException) cause;
            return this.handleFeignException(feignException);
        } else {
            log.error("!!!! Hystrix熔断错误", e);
            return R.error(ResultEnum.ERROR.getCode(), ResultEnum.ERROR.getMessage());
        }
    }

    @ExceptionHandler({FeignException.class})
    public R handleFeignException(FeignException e) {
        log.error("!!!! 远程服务错误", e);
        JSONObject respObj = JSON.parseObject(e.contentUTF8());
        String respMessage = respObj.getString("message");
        int code = ResultEnum.REMOTE_SERVICE_ERROR.getCode();
        String message = StringUtils.isBlank(respMessage)
                ? ResultEnum.REMOTE_SERVICE_ERROR.getMessage() : respMessage;
        return R.error(code, message);
    }

    @ExceptionHandler(Exception.class)
    public R handleException(Exception e) {
        log.error("!!!! 未知异常", e);
        return R.error(ResultEnum.ERROR.getCode(), ResultEnum.ERROR.getMessage());
    }
}