这篇文章将为大家详细讲解有关springboot中怎么自定义异常处理,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
全局异常处理
1、定义handler
@RestControllerAdvice
public
class SelfExceptionHandler {
/**
* 处理Exception
*
@param
e
*
@return
*/
@ExceptionHandler(Exception.
class)
public
Result handleServiceException(Exception
e) {
e.printStackTrace();
return
new
Result(
e
);
}
}
2、写业务的地方抛出异常
throw new Exception("xxx");
自定义异常处理,其实就是自定义一个异常类,例如:BusinessException
然后替换掉handler里面对应的地方
@RestControllerAdvice
public
class SelfExceptionHandler {
/**
* 处理Exception
*
@param
e
*
@return
*/
@ExceptionHandler(
BusinessException.
class)
public
Result handleServiceException(
BusinessException
e) {
e.printStackTrace();
return
new
Result(
e
);
}
}
如果你想把处理结果渲染到页面,可以把
@RestControllerAdvice改成
@ControllerAdvice,
然后添加如下方法:
@ExceptionHandler(Exception.
class)
public ModelAndView handleServiceException(Exception
e) {
ModelAndView
modelAndView =
new ModelAndView();
modelAndView.setViewName(
"500");
modelAndView.addObject(
"code",
e.getMessage());
return
modelAndView;
}
关于springboot中怎么自定义异常处理就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。