在项目中,经常有一些业务需要抛出异常,但是如果后台直接抛出throw new Exception的话,前端就很难看,对用户提示也不够友好,今天我们就来解决这个问题。
先建立一个工程,模拟将异常抛出。如下:
@RestController
public class DemoController {
@GetMapping("test")
public String test() throws Exception{
if(true){
throw new Exception("error");
}
return "ok";
}
}
前端用浏览器请求下,看看界面什么样子:
@ControllerAdvice 和 @ExceptionHandler
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler
@ResponseBody
@ResponseStatus(HttpStatus.OK)
public ResultDto globalException(HttpServletResponse response, Exception ex){
log.info("ExceptionHandler...");
log.info("错误代码:"