我们在做微服务调用的时候,各个服务相互调用难免会出现一些异常。那我们该怎么去把这些异常友好的显示出来。直接贴代码出来
第一个自定义的异常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;
}
}