Spring MVC + dubbo分布式系统基于全局配置的异常处理器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_30038111/article/details/83213661

使用@ControllerAdvice/@RestControllerAdvice配合@ExceptionHandler注解配置全局的异常处理器,处理调用dubbo服务时的Exception

测试代码基于Spring MVC + dubbo的分布式项目,为了简单起见,代码不太完整,只是想引导一下使用dubbo设计架构时,异常处理可以这样处理。

注:JsonResultResultStatus是响应实体,不必过多关注;对于系统中的异常,根据实际的情况,实现不同的异常即可,本文中为了简便,使用了RuntimeExceptionFileNotFoundException。由于能力有限,异常处理的解决方案只能给到这里,请各位大佬多多指教。

全局异常处理器

@ControllerAdvice
public class ExceptionHandle {
    private static final Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);
    
    @ResponseBody
    @ExceptionHandler(RuntimeException.class)
    public Object handleRuntimeException(Exception e) {
        logger.info(e.toString());
        return JsonResult.fail(new ResultStatus(-1, e.toString()));
    }
    @ResponseBody
    @ExceptionHandler(FileNotFoundException.class)
    public Object handleFileNotFoundException(Exception e){
        logger.info(e.toString());
        return JsonResult.fail(new ResultStatus(-1, e.toString()));
    }
}

Controller

@Controller
@RequestMapping("/exception")
public class ExceptionController {
    @Resource
    private ExceptionService exceptionService ;

    @ResponseBody
    @RequestMapping(value = "/runtime")
    public Object runtime() {
        exceptionService.testRuntimeException();
        return JsonResult.success();
    }

	/**
     * 一般此处不会直接抛出异常
     */
    @ResponseBody
    @RequestMapping(value = "/check")
    public Object check() throws FileNotFoundException {
        exceptionService.testFileNotFoundException();
        return JsonResult.success();
    }
}

Service

@Service("exceptionService")
public class ExceptionServiceImpl implements ExceptionService {
	@Override
	 public void testRuntimeException() {
	     throw new RuntimeException("这里有点错误哦");
	 }
	 @Override
	 public void testFileNotFoundException() throws FileNotFoundException {
	     throw new FileNotFoundException("这里有点错误哦");
	 }
 }

dubbo服务注册和消费

<!-- 服务消费配置 -->
<dubbo:reference id="exceptionService" interface="com.xxx.ExceptionService" check="false"  retries="${dubbo.retry}" timeout="5000"/>
<!-- 服务注册配置 -->
<dubbo:service interface="com.xxx.ExceptionService" ref="exceptionService" timeout="${dubbo.service.timeout}" />

请求结果

{
  "code": -1,
  "msg": "java.io.RuntimeException: 这里有点错误哦"
}
{
  "code": -1,
  "msg": "java.io.FileNotFoundException: 这里有点错误哦"
}

猜你喜欢

转载自blog.csdn.net/qq_30038111/article/details/83213661