异常处理@RestControllerAdvice

public class SystemException extends RuntimeException {

	private static final long serialVersionUID = 4291619210980164433L;

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

切面

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Slf4j
@Aspect
@Component
public class ErrorLogAspect {

    private static final String CUT = "@within(restController) || @within(service)";


    @Pointcut(value = CUT)
    public void slsLog(){}


    @AfterThrowing(value = "slsLog()",throwing = "exception")
    public void doAfterThrowingAdvice(JoinPoint joinPoint, Throwable exception){
        log.error("ERROR LOG ====> " ,exception);
    }
}


import com.jhd.merchant.mall.exception.NotFoundException;
import com.jhd.merchant.mall.exception.SystemException;
import com.jhd.merchant.mall.exception.TokenInvalidException;
import com.jhd.merchant.mall.model.ApiResponse;
import com.jhd.merchant.mall.model.BaseResponse;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Slf4j
@RestControllerAdvice
public class AdviceExceptionHandler {

    @ExceptionHandler(FeignException.class)
    public String feignClient(FeignException exception, HttpServletResponse response) {
        response.setStatus(exception.status());
        return exception.getMessage().substring(exception.getMessage().indexOf("content:\n") + 9);
    }

    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(NotFoundException.class)
    public ApiResponse handleException(NotFoundException e) {
        return ApiResponse.notFound().setMessage(e.getMessage());
    }

    @ResponseStatus(HttpStatus.FORBIDDEN)
    @ExceptionHandler(TokenInvalidException.class)
    public BaseResponse handleTokenInvalidException(TokenInvalidException e) {
        return ApiResponse.forbidden().setMessage(e.getMessage());
    }

    @ResponseStatus(value = HttpStatus.OK)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ApiResponse handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        log.warn("HttpMessageNotReadableException bad request ", e);
        ApiResponse apiResponse = ApiResponse.badRequest();
        apiResponse.setMessage("请求错误,请检查参数格式");
        return apiResponse;
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResponse handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        final List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        StringBuilder s = new StringBuilder();
        if (!ObjectUtils.isEmpty(fieldErrors)){
            for ( FieldError fieldError: fieldErrors) {
                s.append("[").append(fieldError.getField()).append(fieldError.getDefaultMessage()).append("]");
            }
        }
        final List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        if (!ObjectUtils.isEmpty(allErrors)){
            for ( ObjectError fieldError: allErrors) { // 排除上面已经加过的 FieldError
                if (!(fieldError  instanceof  FieldError)){
                    s.append("[").append(fieldError.getObjectName()).append(fieldError.getDefaultMessage()).append("]");
                }
            }
        }
        return ApiResponse.serverError().setMessage(s.toString());
    }
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public ApiResponse handleException(Exception e) {
        return ApiResponse.serverError().setMessage("There is a system error");
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(SystemException.class)
    public ApiResponse handleSystemException(SystemException e) {
        return ApiResponse.serverError().setMessage(e.getMessage());
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值