springboot接口异常处理(个人笔记,非教程)

package com.pjw.zhengyouyuan.common;


import com.fasterxml.jackson.core.JsonParseException;
import com.pjw.zhengyouyuan.exception.HttpException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
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 javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@ResponseBody
@ControllerAdvice
public class ExceptionHandlerAdvice {

    @ExceptionHandler(Exception.class)
    public HttpResponse handleExecption(Exception exception) {
        exception.printStackTrace();
        return HttpResponse.error();
    }


    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public HttpResponse handleExecption(HttpRequestMethodNotSupportedException exception, HttpServletRequest request) {
        String method = request.getMethod();
        String[] supportMethods = exception.getSupportedMethods();
        String message = "请求方式错误,正确的请求方式为: " + supportMethods[0] + ",实际接受的请求方式为:" + method;
        return HttpResponse.error(HttpResponseCode.METHOD_ERROR.getCode(), message);
    }

    @ExceptionHandler(JsonParseException.class)
    public HttpResponse handleJsonParseException(JsonParseException e) {
        return HttpResponse.error(HttpResponseCode.PARAMS_ERROR);
    }

    // 请求体要求必须传时,前台没传则报次错误
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public HttpResponse handleHttpMessageNotReadableException(HttpMessageNotReadableException exception) {
        exception.printStackTrace();
        return HttpResponse.error(HttpResponseCode.PARAMS_ERROR);
    }

    @ExceptionHandler(EmptyResultDataAccessException.class)
    public HttpResponse handleEmptyResultDataAccessException(EmptyResultDataAccessException exception) {
        return HttpResponse.error(HttpResponseCode.NO_DATA);
    }

    /**
     * 参数校验不通过错误拦截
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(value = BindException.class)  // 对于表单提交有效,对于以json格式提交将会失效
    public HttpResponse handleBindException(BindException exception) {

        List<ObjectError> all = exception.getAllErrors();

        String message = "";

        for (ObjectError e : all) {

            String msg = e.getDefaultMessage();
            message += msg + ";";
        }

        return HttpResponse.error(HttpResponseCode.PARAMS_ERROR.getCode(), message);
    }

    @ExceptionHandler(HttpException.class)
    public HttpResponse handleHttpException(HttpException exception) {
        String msg = exception.getMessage();
        return HttpResponse.error(exception.getCode(), msg);
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public HttpResponse handleMissingServletRequestParameterException(MissingServletRequestParameterException exception) {
        String parameterName = exception.getParameterName();
        String msg = parameterName + "不能为空";
        return HttpResponse.error(HttpResponseCode.PARAMS_ERROR.getCode(), msg);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class) // 前端提交的方式为json格式有效,出现异常时会被该异常类处理
    public HttpResponse handleMethodArgumentNotValidException(MethodArgumentNotValidException exception) {

        List<ObjectError> allErrors = exception.getBindingResult().getAllErrors();
        String message = allErrors.stream().map(s -> s.getDefaultMessage()).collect(Collectors.joining(";"));
        return HttpResponse.error(HttpResponseCode.PARAMS_ERROR.getCode(),message);
    }


    @ExceptionHandler(ConstraintViolationException.class)  // @NotBlank @NotNull @NotEmpty
    public HttpResponse handleConstraintDeclarationException(ConstraintViolationException exception) {


        String message = "";

        Set<ConstraintViolation<?>> va = exception.getConstraintViolations();
        for (ConstraintViolation item : va) {
            message += item.getMessageTemplate() + ";";
        }

        return HttpResponse.error(HttpResponseCode.PARAMS_ERROR.getCode(), message);
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值