全局异常捕获处理

前言:之前遇到过service层进行数据验证后要返回给前端一个错误信息,把消息先返回给controller层再用统一返回格式返还给前端,总感觉怪怪的.下面通过全局异常捕获处理来解决这个问题

异常捕获处理类

package com.futuredata.web.assess.exception;

import com.futuredata.cloud.common.vo.Result;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Set;

@RestControllerAdvice
public class GlobalExceptionHandler {

	@Bean
	public MethodValidationPostProcessor methodValidationPostProcessor() {
		return new MethodValidationPostProcessor();
	}

	/**
	 * 400 - Bad Request 参数类型错误
	 */
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ExceptionHandler(MethodArgumentTypeMismatchException.class)
	public Result<Object> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) {
		e.printStackTrace();
		String errorMsg = e.getMessage() == null ? Arrays.toString(e.getStackTrace()) : e.getMessage();
		return Result.error("参数类型错误", errorMsg);
	}

	/**
	 * 400 - Bad Request 缺少请求参数
	 */
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ExceptionHandler(MissingServletRequestParameterException.class)
	public Result<String> handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
		e.printStackTrace();
		String errorMsg = e.getMessage() == null ? Arrays.toString(e.getStackTrace()) : e.getMessage();
		return Result.error("缺少请求参数", errorMsg);
	}

	/**
	 * 400 - Bad Request 参数解析失败
	 */
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ExceptionHandler(HttpMessageNotReadableException.class)
	public Result<String> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
		e.printStackTrace();
		String errorMsg = e.getMessage() == null ? Arrays.toString(e.getStackTrace()) : e.getMessage();
		return Result.error("参数解析失败", errorMsg);
	}

	/**
	 * 400 - Bad Request 参数验证失败
	 */
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ExceptionHandler(MethodArgumentNotValidException.class)
	public Result<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
		e.printStackTrace();
		String errorMsg = e.getMessage() == null ? Arrays.toString(e.getStackTrace()) : e.getMessage();
		return Result.error("参数验证失败", errorMsg);
	}

	/**
	 * 400 - Bad Request 参数绑定失败
	 */
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ExceptionHandler(BindException.class)
	public Result<String> handleBindException(BindException e) {
		e.printStackTrace();
		String errorMsg = e.getMessage() == null ? Arrays.toString(e.getStackTrace()) : e.getMessage();
		return Result.error("参数绑定失败", errorMsg);
	}

	/**
	 * 400 - Bad Request 参数验证失败
	 */
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ExceptionHandler(ConstraintViolationException.class)
	public Result<String> handleServiceException(ConstraintViolationException e) {
		e.printStackTrace();
		Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
		ConstraintViolation<?> violation = violations.iterator().next();
		String errorMsg = violation.getMessage();
		String errorMsg_1 = e.getMessage() == null ? Arrays.toString(e.getStackTrace()) : e.getMessage();
		return Result.error("参数:" + errorMsg, errorMsg_1);
	}

	/**
	 * 400 - Bad Request 参数验证失败
	 */
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ExceptionHandler(ValidationException.class)
	public Result<String> handleValidationException(ValidationException e) {
		e.printStackTrace();
		String errorMsg = e.getMessage() == null ? Arrays.toString(e.getStackTrace()) : e.getMessage();
		return Result.error("参数验证失败", errorMsg);
	}

	/**
	 * 400 - Bad Request 参数验证失败
	 */
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ExceptionHandler(IllegalArgumentException.class)
	public Result<String> handleIllegalArgumentException(IllegalArgumentException e) {
		e.printStackTrace();
		String errorMsg = e.getMessage() == null ? Arrays.toString(e.getStackTrace()) : e.getMessage();
		return Result.error("参数验证失败", errorMsg);
	}

	/**
	 * 405 - Method Not Allowed 不支持当前请求方法
	 */
	@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
	@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
	public Result<String> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
		e.printStackTrace();
		String errorMsg = e.getMessage() == null ? Arrays.toString(e.getStackTrace()) : e.getMessage();
		return Result.error("不支持当前请求方法", errorMsg);
	}

	/**
	 * 415 - Unsupported Media Type 不支持当前媒体类型
	 */
	@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
	@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
	public Result<String> handleHttpMediaTypeNotSupportedException(Exception e) {
		e.printStackTrace();
		String errorMsg = e.getMessage() == null ? Arrays.toString(e.getStackTrace()) : e.getMessage();
		return Result.error("不支持当前媒体类型", errorMsg);
	}

	@ExceptionHandler(IOException.class)
	public Result<String> handleFileNotFoundException(IOException e) {
		e.printStackTrace();
		String errorMsg = e.getMessage() == null ? Arrays.toString(e.getStackTrace()) : e.getMessage();
		return Result.error("文件读取错误,不存在该文件", errorMsg);
	}

	/**
	 * 500 - Internal Server Error 通用异常
	 */
	@ExceptionHandler(Exception.class)
	public Result<String> handleException400(Exception e) {
		e.printStackTrace();
		String errorMsg = e.getMessage() == null ? Arrays.toString(e.getStackTrace()) : e.getMessage();
		return Result.error("请联系管理员", errorMsg);
	}

	/**
	 * 400 - Internal Server Error 运行时异常
	 */
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ExceptionHandler(RuntimeException.class)
	public Result<String> runtimeException(RuntimeException e) {
		e.printStackTrace();
		String errorMsg = e.getMessage() == null ? Arrays.toString(e.getStackTrace()) : e.getMessage();
		return Result.error(errorMsg);
	}

}

抛出异常的写法

 /**
     * 删除指标
     * @param indexId 指标id
     */
    @Transactional(rollbackFor = Exception.class)
    public void delete(Integer indexId) {
        //删除法律法条
        indexMapper.delLegalByIndexId(indexId);
        //查询该指标数据信息,如果是一级分类,那么先删除分类下面的二级指标
        IndexVo indexVo = indexMapper.getIndexById(indexId);
        if (0==indexVo.getParentId()){
            //获取下级分类列表--如果包含已使用的指标,则不给删除
            List<IndexVo> indexVos = indexMapper.listIndexByParentId(indexId);
            long count = indexVos.stream().filter(e -> "1".equals(e.getStatus())).count();
            if (count>0){
                throw new RuntimeException("删除失败,该分类下存在已生效指标。");
            }else {
                indexMapper.deleteIndexByParentId(indexId);
            }
        }
        indexMapper.deleteIndexById(indexId);
    }

异常返回实体类参考

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.futuredata.cloud.common.vo;

import java.io.Serializable;

public class Result<T> implements Serializable {
    private static final long serialVersionUID = 1L;
    protected int code;
    protected String message;
    protected T data;

    public Result(int code) {
        this.code = code;
    }

    public Result(int code, T data) {
        this.code = code;
        this.data = data;
    }

    public Result(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public Result(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public static <E> Result<E> success() {
        return new Result(200);
    }

    public static <E> Result<E> success(String message) {
        return new Result(200, message);
    }

    public static <E> Result<E> success(E data) {
        return new Result(200, data);
    }

    public static <E> Result<E> success(String message, E data) {
        return new Result(200, message, data);
    }

    public static <E> Result<E> error(E data) {
        return new Result(400, data);
    }

    public static <E> Result<E> error(String message, E data) {
        return new Result(400, message, data);
    }

    public static <E> Result<E> error(String message) {
        return new Result(400, message);
    }

    public Result() {
    }

    public int getCode() {
        return this.code;
    }

    public String getMessage() {
        return this.message;
    }

    public T getData() {
        return this.data;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void setData(T data) {
        this.data = data;
    }
}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值