如何将后端的错误通过接口返回给前端使用。
一、需要后端进行全局异常的捕获
@Slf4j @ControllerAdvice public class GlobalExceptionHandler { /** * 业务异常处理 * * @param e * @return */ @ResponseBody @ExceptionHandler(value = ScmplatformException.class) public Result handleServiceException(ScmplatformException e){ log.error("出现异常", e); Result result = new Result(); result.setMsg(e.getMessage()); result.setCode(e.getCode()); return result; } /** * 运行时异常 * @param e * @return */ @ResponseBody @ExceptionHandler(value = RuntimeException.class) public Result handleArgsException(RuntimeException e){ Result result = new Result(); result.setMsg(e.getMessage()); result.setData(e.getStackTrace()); result.setCode(500); return result; } }
由上述代码可知,我们定义了全部捕获的异常,RuntimeException、ScmplatformException
二、定义全局的异常枚举code 和 message
public enum SystemInfo { //系统类别错误 00100 SYS_SUCCESS(200, ""), SYS_INTERNAL_ERROR(120000100, "系统错误,请稍后重试"), SYS_PARAM_ERROR(120000101, "参数错误"), SYS_DATA_ERROR(120000102, "数据错误"), SYS_USER_NOT_EXISTS(120000103,"用户不存在"), SYS_INVALID_REQUEST(120000104,"非法请求"), SYS_BUSY(120000105, "当前系统繁忙,请稍后重试"), SYS_PATH_NOT_NULL(120000106,"path路径不能为空"), SYS_METHOD_NOT_EXISTS(120000107,"接口未找到该方法"), SYS_INTERFACE_NAME_NOT_NULL(120000108,"接口全限定类名不能为空"), SYS_DIFF_INACCESSIBLE(120000109,"由于无法访问基础值而无法进行比较"), SYS_MAVEN_SETTING(120000110,"maven参数解析错误,请检查maven参数"), SYS_JAR_NOT_EXITS(120000111,"当前路径下jar包不存在,请先下载上传maven坐标下载"), SYS_METHOD_NAME_NOT_NULL(120000112,"方法名称不能为空"), SYS_ENV_NOT_NULL(120000113,"环境不能不能为空"), SYS_PARAMETER_TYPE_NOT_NULL(120000114,"入参类型不能为空"), SYS_PARAMETERS_NOT_NULL(120000115,"入参不能为空") ; private Integer code; private String message; SystemInfo(Integer code, String message) { this.code = code; this.message = message; } public Integer code() { return code; } public String message() { return message; } public String message(String msg) { return msg + message(); } public String messageVal(Object ... args){ return String.format(message,args); } }
三、接口异常抛出去
例如:
if (newReflectBoList.size() <=0){ throw new ScmplatformException(SystemInfo.SYS_METHOD_NOT_EXISTS); } try { list =dubboDataMapper.selectAll(); }catch (RuntimeException e){ e.getStackTrace(); throw new RuntimeException(e.getCause()); }
此时即可进行异常数据透出即可。