我們在做微服務調用的時候,各個服務相互調用難免會出現一些異常。那我們該怎麼去把這些異常友好的顯示出來。直接貼代碼出來
第一個自定義的異常ServiceExceotion之前有寫過點擊查看
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
private final static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 自定義異常處理
* @param ex
* @return
*/
@ExceptionHandler(value = ServiceException.class)
public Map myErrorHandler(ServiceException ex) {
Map<String,Object> map = new HashMap<>(6);
map.put("code", ex.getCode());
map.put("message", ex.getMsg());
map.put("data",ex.getData());
logger.error("自定義異常捕捉異常"+ex.getMessage(),ex);
return map;
}
/**
* 全局異常處理
* @param
* @return
*/
@ExceptionHandler(value = Exception.class)
public Map errorHandler(Exception e) {
Map<String,String> map = new HashMap<>(6);
map.put("code", ResponseUtil.ERROR_CODE);
map.put("message", ResponseUtil.SERVER_TEXT);
map.put("data","");
logger.error("全局異常捕捉異常"+e.getMessage(),e);
return map;
}
/**
* Feign異常處理
* @param e
* @return
*/
@ExceptionHandler(value = FeignException.class)
public Map feignExceptionHandler(FeignException e){
Map<String,String> map = new HashMap<>(6);
map.put("code", ResponseUtil.ERROR_CODE);
map.put("message", ResponseUtil.FEIGN_ERROR_TEXT);
map.put("data",e.getMessage());
logger.error("FEIGN異常"+e.getMessage(),e);
return map;
}
}