1.思考
我知道的后端向前端返回数据的地方有两个。
一是前端访问后端接口很顺利,后端将状态码和信息返回给前端。
二是前端访问后端接口,出现问题抛出异常,抛出异常被全局异常处理将信息返回给前端。
问题就在于抛出的异常这块是如何将信息从后端传递到前端的
2.试验
2.1 控制层
@RestController
@RequestMapping("/Exception")
public class testController {
@GetMapping("/test")
public String test() {
int i = 1 / 0;
return "test exception";
}
}
2.2直接测试
后台对抛出的异常不做处理的话,后台显示信息,而前端不显示。
2.3 全局异常处理类
@Slf4j
@ControllerAdvice
public class GlobalExceptionAdvice {
@ExceptionHandler({Exception.class})
@ResponseBody
public Object handleException(HttpServletRequest request, Exception e) throws Exception {
log.error(e.getMessage(), e);
HashMap<String, Object> map = new HashMap<>();
map.put("message", "全局异常处理" + e.getMessage());
return map;
}
}
2.4测试
访问项目路径,可以发现后端抛出的报错信息传递给前端了
3.自定义异常处理
3.1控制器层
@GetMapping("/test1")
public String test1(){
Boolean flag = true;
if (flag != false) {
throw new TestException("逻辑判断错误-自定义异常类");
}
return "test success";
}
3.2自定义异常
public class TestException extends RuntimeException{
public TestException(String message) {
super(message);
}
}
3.3全局异常处理
@Slf4j
@ControllerAdvice
public class GlobalExceptionAdvice {
@ExceptionHandler({TestException.class})
@ResponseBody
public Object TestException(HttpServletRequest request, Exception e) throws Exception {
log.error(e.getMessage(), e);
HashMap<String, Object> map = new HashMap<>();
map.put("message", "逻辑异常处理--" + e.getMessage());
return map;
}
}
3.4测试
这样就可以在前端返回自己写的异常了。
还可以在全局异常处理中填写上http状态码和code码