全局异常处理器



import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.organization.global.constant.ErrorCode;
import com.organization.global.exception.CodeException;
import com.organization.global.utils.JsonUtils;
import com.organization.global.vo.ErrorResultVo;
import feign.FeignException;
import feign.RetryableException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingRequestHeaderException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class ControllerExceptionHandleAdvice {

    @ExceptionHandler(CodeException.class)
    public ResponseEntity<ErrorResultVo> handleCodeException(CodeException e) {
        if (e.getCause() != null) {
            log.error(e.getMessage(), e);
        }
        HttpStatus httpStatus = e.getHttpStatus();
        if (httpStatus == null) {
            httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        }

        return ResponseEntity.status(httpStatus).body(new ErrorResultVo(e.getCode(), e.getMessage()));
    }

    @ExceptionHandler(RetryableException.class)
    public ResponseEntity<ErrorResultVo> handleException(RetryableException e) {
        String message = e.getMessage();
        log.error(message,e);
        return ResponseEntity.internalServerError()
                .body(new ErrorResultVo(ErrorCode.INTERNET_ERROR, "网路请求出错:"+message));

    }


    @ExceptionHandler(FeignException.class)
    public ResponseEntity<ErrorResultVo> handleException(FeignException e) {

        try {
            String body = e.contentUTF8();
            ErrorResultVo errorResultVo = JsonUtils.jsonToObj(body, ErrorResultVo.class);
            log.error(e.getMessage(), e);
            return ResponseEntity.status(e.status())
                    .body(errorResultVo);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseEntity.internalServerError()
                    .body(new ErrorResultVo(HttpStatus.INTERNAL_SERVER_ERROR.name(), "内部错误!"));
        }

    }
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorResultVo> handleException(Exception e) {
        log.error(e.getMessage(), e);
        return ResponseEntity.internalServerError()
                .body(new ErrorResultVo(HttpStatus.INTERNAL_SERVER_ERROR.name(), "内部错误!"));
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ErrorResultVo> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        FieldError fieldError = e.getBindingResult().getFieldError();
        return ResponseEntity.badRequest()
                .body(
                        new ErrorResultVo(HttpStatus.BAD_REQUEST.name(),
                                fieldError == null ? "参数错误!" : fieldError.getDefaultMessage()));
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ResponseEntity<ErrorResultVo> handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        return ResponseEntity.badRequest()
                .body(
                        new ErrorResultVo(HttpStatus.BAD_REQUEST.name(),
                                "缺少参数“" + e.getParameterName() + "”!"));
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseEntity<ErrorResultVo> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        String message = "数据格式错误!";
        Throwable cause = e.getCause();
        if (cause instanceof InvalidFormatException) {
            InvalidFormatException causeException = (InvalidFormatException) cause;
            message += "错误值:“" + causeException.getValue() + "”";
        }

        return ResponseEntity.badRequest()
                .body(
                        new ErrorResultVo(HttpStatus.BAD_REQUEST.name(),
                                message));
    }

    @ExceptionHandler(MissingRequestHeaderException.class)
    public ResponseEntity<ErrorResultVo> handleHttpMessageNotReadableException(MissingRequestHeaderException e) {
        return ResponseEntity.badRequest()
                .body(
                        new ErrorResultVo(HttpStatus.BAD_REQUEST.name(),
                                "Header缺少:" + e.getHeaderName()));
    }
}

自定义异常



import org.springframework.http.HttpStatus;

public class HttpStatusException extends Exception {

    private HttpStatus httpStatus;
    private String code;

    public HttpStatusException(String code, String message) {
        super(message);
        this.code = code;
        this.httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
    }


    public HttpStatusException(String code, String message, Throwable cause) {
        super(message, cause);
        this.code = code;
        this.httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
    }

    public HttpStatusException(HttpStatus httpStatus, String code, String message) {
        super(message);
        this.code = code;
        this.httpStatus = httpStatus;
    }


    public HttpStatusException(HttpStatus httpStatus, String code, String message, Throwable cause) {
        super(message, cause);
        this.code = code;
        this.httpStatus = httpStatus;
    }


    public HttpStatus getHttpStatus() {
        return httpStatus;
    }

    public String getCode() {
        return code;
    }
}

轻量级返回对象



/**
 * 轻量级的 对象,只读不可以改 只有get方法  全是 final类型
 * @param code
 * @param message
 */
public record ErrorResultVo(String code, String message) {

}

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值