SpringBoot实现统一异常处理

分享知识 传递快乐

 

Spring Boot 实现统一异常处理的方法主要有以下两种:

  • 使用@ControllerAdvice和@ExceptionHandler注解
  • 使用ErrorController类来实现

 

1、使用@ControllerAdvice和@ExceptionHandler注解

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.ModelAndView;

import com.xh.common.util.map.PageData;
import com.xh.common.util.result.Result;

@ControllerAdvice
public class LocalExceptionHandler {

	@ExceptionHandler(ResultException.class)
	@ResponseBody
	public Result handleResultException(ResultException e) {
		return Result.exception("500", "操作异常", e.getMessage());
	}
	
	@ExceptionHandler(MaxUploadSizeExceededException.class)
	public ModelAndView handleResultException(MaxUploadSizeExceededException e) {
		PageData.entityToMap(Result.exception("403", "上传文件过大"));
		return new ModelAndView("", PageData.getMap());
	}

	
	@ExceptionHandler(Exception.class)
	@ResponseBody
	public Result handleResultException(Exception e) {
		return Result.exception("500", "操作异常", e.getMessage());
	}

}

说明:

  1、注解@ControllerAdvice表示这是一个控制器增强类,当控制器发生异常就会被此拦截器被拦截。

  2、注解@ExceptionHandler 定义拦截的异常类,可以获取抛出的异常信息。这里可以定义多个拦截方法,拦截不同的异常类,并且可以获取抛出的异常信息,自由度更大。

 

2、使用ErrorController类来实现

@Controller
public class UserErrorController implements ErrorController {
    @Autowired
    private ErrorAttributes errorAttributes;

    @RequestMapping("/error")
    public String handleError(HttpServletRequest request){
        //错误详情
        ServletWebRequest servletWebRequest = new ServletWebRequest(request);
        Map<String, Object> errorAttributes = this.errorAttributes.getErrorAttributes(servletWebRequest, true);
        //根据状态码返回到对应页面
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if(statusCode == 400){
            return "/400";
        }else if(statusCode == 403){
            return "/403";
        }else if(statusCode == 404){
            return "/404";
        }else{
            return "/500";
        }
    }
    @Override
    public String getErrorPath() {
        return "/error";
    }
}

 

 

 

 

 

 

—————————
如有不足请留言指正
相互学习,共同进步

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

旷野历程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值