码上敲享录 > SpringBoot常见问题详解 > springboot如何全局捕捉异常

springboot如何全局捕捉异常

上一章章节目录下一章 2020-01-15已有2619人阅读 评论(0)

springboot如何全局捕捉异常


解决方法:

下面的@ExceptionHandler(Exception.class)表示捕捉没有在代码中try catch的异常

@ExceptionHandler(SurvetException.class)表示只捕捉自定义的异常,SurvetException是我自定义的继承Exception的类,如果执行了@ExceptionHandler(SurvetException.class)中的代码就不再执行@ExceptionHandler(Exception.class)中的代码


import com.alibaba.fastjson.JSON;

import com.thinkcc.survet.base.utils.RspStatusAndMsg;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.http.HttpStatus;

import org.springframework.validation.BindException;

import org.springframework.validation.FieldError;

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.servlet.http.HttpServletResponse;

import java.util.List;

@ControllerAdvice

public class GrobalExceptionHandler {


   private static Logger log= LoggerFactory.getLogger(GrobalExceptionHandler.class);


   @ExceptionHandler(SurvetException.class)

   @ResponseBody

   public RspStatusAndMsg grobalExceptionHandler(HttpServletRequest request, SurvetException ex) {

       RspStatusAndMsg rspStatusAndMsg = new RspStatusAndMsg();

       if (ex.getErrorCode() == null) {

           rspStatusAndMsg.setErrorCode("10009");

       } else {

           rspStatusAndMsg.setErrorCode(ex.getErrorCode());

       }

       rspStatusAndMsg.setMessage(ex.getMessage());

       rspStatusAndMsg.setStatus(false);

       return rspStatusAndMsg;

   }


   @ExceptionHandler(Exception.class)

   @ResponseBody

   public RspStatusAndMsg BindExceptionHandler(HttpServletRequest request, Exception ex) {

       RspStatusAndMsg rspStatusAndMsg = new RspStatusAndMsg();

       rspStatusAndMsg.setErrorCode(500);

       rspStatusAndMsg.setMessage("服务忙,请稍后重试");

       rspStatusAndMsg.setStatus(false);

       log.error(ex.getMessage(),ex);

       if (log.isDebugEnabled()){

           ex.printStackTrace();

       }

       return rspStatusAndMsg;

   }

}


向大家推荐《Activiti工作流实战教程》:https://xiaozhuanlan.com/activiti
0

有建议,请留言!

  • *您的姓名:

  • *所在城市:

  • *您的联系电话:

    *您的QQ:

  • 咨询问题:

  • 提 交