当前位置: 首页 > 后端技术 > Java

异常这样处理,更加人性化

时间:2023-04-01 22:10:13 Java

在项目中,经常会有一些业务需要抛出异常,但是如果后台直接抛出thrownewException,前端就丑了,用户提示不够友好。今天我们就来解决这个问题。先创建一个项目,模拟会抛出异常。如下:@RestControllerpublicclassDemoController{@GetMapping("test")publicStringtest()throwsException{if(true){thrownewException("error");}返回“确定”;}}前端用浏览器请求,看界面是什么样的:@ControllerAdvice和@ExceptionHandler@Slf4j@ControllerAdvicepublicclassGlobalExceptionHandler{@ExceptionHandler@ResponseBody@ResponseStatus(HttpStatus.OK)publicResultDtoglobalException(HttpServletResponseresponse,Exception.inp...");log.info("错误代码:"+response.getStatus());ResultDtoresultDto=newResultDto();resultDto.setCode(0);resultDto.setMsg(ex.getMessage());resultDto.setData(null);returnresultDto;}}定义一个返回给前端的通用结构@DatapublicclassResultDto{//请求结果0表示失败,其他为成功privateintcode;//失败消息privateStringmsg;//实际返回数据给前端privateObjectdata;}然后我们写一个控制器来模拟抛出异常@GetMapping("test1")publicStringtest1()throwsException{if(true){thrownewNullPointerException("NullPointerException");}return"ok";}@GetMapping("test2")publicStringtest2()throwsException{if(true){thrownewRuntimeException("RuntimeException");}return"ok";}@GetMapping("test3")publicStringtest3()throwsMyException{if(true){//不能直接抛出Exception,否则捕获不到,可以定义异常你自己thrownewMyException("MyException");}return"ok";}请求看看postman返回什么{"code":0,"msg":"NullPointerException","data":null}在实际业务中,我们通常会返回自定义异常,所以我会定义一个异常我自己的并单独处理它:publicclassMyExceptionextendsException{publicMyException(){super();}publicMyException(Stringmessage){super(message);}publicMyException(Stringmessage,Throwablecause){super(message,cause);}publicMyException(可抛出的原因){超级(原因);}protectedMyException(Stringmessage,Throwablecause,booleanenableSuppression,booleanwritableStackTrace){super(message,cause,enableSuppression,writableStackTrace);}}然后在GlobalExceptionHandler中增加对MyException的处理:@ExceptionHandler.MyExceptionclass)@ResponseBody@ResponseStatus(HttpStatus.OK)publicResultDtomyException(HttpServletResponseresponse,MyExceptionex){log.info("MyExceptionHandler...");log.info("错误代码:"+response.getStatus());ResultDtoresultDto=newResultDto();resultDto.setCode(0);resultDto.setMsg(ex.getMessage());resultDto.setData(null);returnresultDto;}请求http://localhost:8080/test3看前端输出了什么{"code":0,"msg":"MyException","data":null}这里不清楚是否是myException或者globalException,但是如果看一下后台的日志输出,就会清楚的看到,我们在处理各种异常的时候,springboot会优先处理子类异常。更多java原著阅读:https://javawu.com