91名师指路-头部
91名师指路

spring boot 全局异常处理,以及自定义异常

由于某些原因,现在不支持支付宝支付,如需要购买源码请加博主微信进行购买,微信号:13248254750

前提:我项目框架是 spring cloud 

1 配置全局异常处理类。

package com.mszl.candidate.exception;

import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import com.manulife.utils.BusinessUtils;
import com.manulife.utils.ReturnMsgUtils;
import lombok.extern.slf4j.Slf4j;

@ControllerAdvice
@Slf4j
public class GlobalDefultExceptionHandler {

//声明要捕获的异常
@ExceptionHandler(Exception.class)
@ResponseBody
public ReturnMsgUtils defultExcepitonHandler(HttpServletRequest request, Exception e) {
ReturnMsgUtils msg=null;
if(e instanceof BusinessException) {
BusinessException businessException = (BusinessException)e;
msg=new ReturnMsgUtils(businessException.getCode(), businessException.getMessage());
return msg;
} else{
Throwable t = e;
StringWriter stringWriter= new StringWriter();
PrintWriter writer= new PrintWriter(stringWriter);
t.printStackTrace(writer);
StringBuffer buffer= stringWriter.getBuffer();
log.error(buffer.toString());
msg = new ReturnMsgUtils(BusinessUtils.BUSINESS_CODE_201, BusinessUtils.BUSINESS_MSG_202,buffer.toString());
return msg;
}
}




}

说明:

定义一个处理类,使用@ControllerAdvice注解。

@ControllerAdvice注解:控制器增强,一个被@Component注册的组件。

配合@ExceptionHandler来增强所有的@requestMapping方法。


2 自定义异常处理。如我们需要人为的抛出错误来进行事务的回滚

package com.mszl.candidate.exception;

public class BusinessException extends RuntimeException{

private static final long serialVersionUID = 1L;

// 自定义错误码
private Integer code;

// 自定义构造器,只保留一个,让其必须输入错误码及内容
public BusinessException(int code, String msg) {
super(msg);
this.code = code;
}

public Integer getCode() {
return code;
}

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



}

3 还要最最关键的一步,要在service实现层加上 @Transactional 注解,否则事务不会进行回滚。


2019-08-23 15:04:26     阅读(1025)

名师出品,必属精品    https://www.91mszl.com

联系博主    
用户登录遮罩层
x

账号登录

91名师指路-底部