springboot之统一异常封装

一:统一返回实体对象

@JsonInclude(Include.NON_NULL)
public class ResponseObject implements Serializable {

    private static final long serialVersionUID = 1L;
    private Integer code = 0;
    private String message = "success";
    private Long time = System.currentTimeMillis();
    private String version = "1.0.0";
    private Object body = new HashMap<String, Object>();
    private String requestParams;
    private String exceptionInfo;

    /**
     * code默认为成功
     */
    public ResponseObject() {
        //默认为成功
    	this.code = ResponseCode.SUCC.getCode();
    }

    public ResponseObject(Integer code, String message) {
    	this.code = code;
        this.message = message;
    }

    public ResponseObject(Integer code, Object body) {
    	this.code = code;
        this.body = body;
    }

    public ResponseObject(ResponseCode errorCode) {
        this.code = errorCode.getCode();
        this.message = errorCode.getMessage();
    }

    public ResponseObject(ResponseCode errorCode, Map<String, Object> body) {
        this.code = errorCode.getCode();
        this.message = errorCode.getMessage();
        this.body = body;

    }

    public Integer getCode() {
        return code;
    }
    public void setCode(Integer code) {
        this.code = code;
    }
    public void setSucc() {
        this.code = ResponseCode.SUCC.getCode();
    }

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

    public Long getTime() {
        return time;
    }

    public void setTime(Long time) {
        this.time = time;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }
	public String getRequestParams() {
		return requestParams;
	}
	public void setRequestParams(String requestParams) {
		this.requestParams = requestParams;
	}
	public String getExceptionInfo() {
		return exceptionInfo;
	}
	public void setExceptionInfo(String exceptionInfo) {
		this.exceptionInfo = exceptionInfo;
	}

    @SuppressWarnings("unchecked")
	public <T>T getBody() {
        return (T) body;
    }

    public void setBody(Object body) {
        this.body = body;
    }
    /**
     * 通用转换body对象的类型
     * @param clazz
     * @return
     */
    @SuppressWarnings("unchecked")
	public <T>T convertBody(Class<?> clazz) {
    	String result = JsonUtil.toString(this.body);
    	if (this.body instanceof List) {
            this.body = JsonUtil.toList(result, clazz);
    	} else {
    		this.body = JsonUtil.toObject(result, clazz);
    	}
        return (T) this.body;
    }
}

全局异常处理类

/**
 * @Author:liming
 * @Package:com.ms.biz.x.exception
 * @name:GlobalExceptionHandler
 * @Date:2023/11/7 15:54
 * @Filename:GlobalExceptionHandler
 */

@RestControllerAdvice
public class GlobalExceptionHandler{
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    public GlobalExceptionHandler() {}
     //文件大小捕获异常:MaxUploadSizeExceededException
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ResponseObject handlerMaxUploadFile(MaxUploadSizeExceededException ex) {
        ResponseObject = new ResponseObject();
        log.error("异常信息 {} ", ex.getMessage());
        frame.setCode(-1);
        frame.setMessage("单文件超过文件大小限制XM了!");
        frame.setBody("单文件超过文件大小限制XM了!");
        frame.setExceptionInfo("单文件超过文件大小限制XM了!");
        return frame;
    }
     /**
     * spring统一捕获sql异常
     */
    @ExceptionHandler(DataIntegrityViolationException.class)
    @ResponseBody
    public ResponseObject dataIntegrityViolationException(DataIntegrityViolationException e) {
        ResponseObject frame = new ResponseFrame();
        // 异常信息类
        Throwable cause = e.getCause();
        // 字段超长
        if (cause.getClass().equals(SQLIntegrityConstraintViolationException.class)) {
            frame.setMessage("数据库操作异常 数据已存在!");
            String localizedMessage = cause.getLocalizedMessage();
            frame.setBody(localizedMessage);
            // 数据库插入异常
        } else if (cause.getClass().equals(SQLSyntaxErrorException.class)) {
            frame.setMessage("数据库插入异常");
        }
        frame.setCode(-1);
        log.warn("数据库操作异常");
        return frame;
    }
/**
参数非法异常处理 如400
*/
    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public ResponseObjecthandleMethodArgumentNotValidException(Exception exception) {
        StringBuilder errorInfo = new StringBuilder();
        BindingResult bindingResult = null;
        if (exception instanceof MethodArgumentNotValidException) {
            bindingResult = ((MethodArgumentNotValidException) exception).getBindingResult();
        }
        if (exception instanceof BindException) {
            bindingResult = ((BindException) exception).getBindingResult();
        }
        for (int i = 0; i < bindingResult.getFieldErrors().size(); i++) {
            if (i > 0) {
                errorInfo.append(",");
            }
            FieldError fieldError = bindingResult.getFieldErrors().get(i);
            errorInfo.append(fieldError.getField()).append(" :").append(fieldError.getDefaultMessage());
        }
        log.error(errorInfo.toString());
        //这里返回自己的Result的结果类。
        ResponseObject = new ResponseObject();
        frame.setBody(errorInfo.toString());
        frame.setCode(-1);
//        frame.setMessage("fail");
        String[] split = errorInfo.toString().split(" :");
        String error = split[1];
        frame.setMessage(error);
        return frame;
    }
}
// 捕获其他未处理的异常,并返回错误信息
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseObject handleUncaughtException(Exception ex) {

        return createErrorResponse(-1, "系统内部错误: ", ex.getMessage());
    }

    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseObject handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException ex) {

        return createErrorResponse(-1, "请求参数有误: ", ex.getMessage());
    }

    private ResponseObject createErrorResponse(int code, String message, String detils) {
        ResponseObject  frame = new ResponseFrame();
        frame.setMessage(message);
        frame.setCode(code);
        frame.setBody(detils);
        return frame;
    }

全局控制参数配置

server:
  port: 9010
  tomcat:
    max-swallow-size: -1  # tomcat默认大小2M,超过2M的文件不会被捕获,需要调整此处大小为10MB或者-1即可
management:
  endpoints:
    web:
      exposure:
        include=refresh: refresh

spring:
  application:
    name: xxx
  datasource:
    dynamic:
      primary: X #默认主数据库
      strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
      datasource:
        x:
          url: jdbc:oracle:thin:@1.196.2.73:1528:cjhx
          username: 21212
          password: 1212
          driver-class-name: oracle.jdbc.OracleDriver
        y:
          url: jdbc:oracle:thin:@1.190.X.X:1528:cjhx
          username: 12
          password: 1212
          driver-class-name: oracle.jdbc.OracleDriver
  servlet:
    multipart:
      max-file-size: XMB     # 文件上传大小限制为XMB
      max-request-size: XMB  # 请求大小限制为XMB

ps:代码中JsonUtil可以访问链接进去索取
以上的是SpringBoot之远程调用的三大方式 若需完整代码 可识别二维码后 给您发代码。
索取json封装转化工具类
在这里插入图片描述

  • 9
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值