重写异常处理

package org.cango.cjs.exception;

import org.cango.base.utils.LogUtil;
import org.cango.mid.base.model.Result;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

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

@RestControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CJSExceptionHandler {

    private void setResponse(int code) {
        RequestAttributes res = RequestContextHolder.getRequestAttributes();
        if (res instanceof ServletRequestAttributes) {
            ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse().setStatus(code);
        } else {
            HttpServletResponse resp = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            resp.setStatus(code);
        }
    }

    // MethodArgumentNotValidException 异常
    @ExceptionHandler(org.springframework.web.bind.MethodArgumentNotValidException.class)
    public Result<Object> handleValidleException(org.springframework.web.bind.MethodArgumentNotValidException e) {
        LogUtil.error("参数合法校验异常 Exception :", e);
        setResponse(400);
        BindingResult bindingResult = e.getBindingResult();
        String message = "";
        List<FieldError> errors = bindingResult.getFieldErrors();
        for (int i = 0; i < errors.size(); i++) {
            if (i == errors.size() - 1) {
                message = message + errors.get(i).getDefaultMessage();
            } else {
                message = message + errors.get(i).getDefaultMessage() + ",";
            }
        }
        return new Result<Object>(ErrorCode.PARAM_ERROR.getCode(), message, null);
    }


    @ExceptionHandler(org.springframework.http.converter.HttpMessageNotReadableException.class)
    public Result<Object> handleConverterException(org.springframework.http.converter.HttpMessageNotReadableException e) {
        LogUtil.error("参数转化异常 Exception :", e);
        setResponse(400);
        return new Result<Object>(ErrorCode.PARAM_ERROR.getCode(), e.getMessage(), null);
    }
}
posted @ 2024-04-09 15:37  亲爱的阿道君  阅读(3)  评论(0编辑  收藏  举报