1. 程式人生 > >Spring MVC + dubbo分散式系統基於全域性配置的異常處理器

Spring MVC + dubbo分散式系統基於全域性配置的異常處理器

使用@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: 這裡有點錯誤哦"
}