项目当中我们经常会处理异常,所以需要在代码中try..catch。这样就会造成两个问题:1.把后台的报错直接给前端 页面不美观 2.我们频繁的写try..catch也挺麻烦,所以我们需要用到全局异常处理,全局异常处理有很多种办法 今天用的是spring的全局异常处理,话不多说 直接上代码!
1.如果需要自定义异常的 请参考
public class BaseException extends Exception {
/**
* 自定义认证异常
*/
public AuthorizeException(String message){
super(message);
}
}
2.如果不需要自定义异常 直接设置全局异常
/**
* 全局异常处理器
*/
@RestControllerAdvice
public class GlobalExceptionHandler
{
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 空指针异常
*/
@ExceptionHandler(NullPointerException.class)
public AjaxResult businessException(NullPointerException e)
{
if (StringUtils.isNull(e.getCode()))
{
return Result.error(e.getMessage());
}
return Result.error(e.getCode(), e.getMessage());
}
/**
* 其他异常
*/
@ExceptionHandler(Exception.class)
public AjaxResult handleException(Exception e)
{
log.error(e.getMessage(), e);
return Result.error(HttpStatus.ERROR,"系统异常");
}
/**
* 自定义验证异常
*/
@ExceptionHandler(PreAuthorizeException.class)
public AjaxResult preAuthorizeException(PreAuthorizeException e)
{
return Result.error("没有权限,请联系管理员授权");
}
}
3.测试
@RestController
@RequestMapping("/test")
public class GlobalController {
@RequestMapping("/testError")
public ResponseEntity<?> testError() {
//代码中可以加一个判断 直接throw出异常
throw new HospitalException("测试类");
}
}