在我的项目中,常常有一些业务须要抛出异样,然而如果后盾间接抛出throw new Exception的话,前端就很难看,对用户提醒也不够敌对,明天咱们就来解决这个问题。
先建设一个工程,模仿将异样抛出。如下:
@RestControllerpublic class DemoController { @GetMapping("test") public String test() throws Exception{ if(true){ throw new Exception("error"); } return "ok"; }}
前端用浏览器申请下,看看界面什么样子:
@ControllerAdvice 和 @ExceptionHandler
@Slf4j@ControllerAdvicepublic class GlobalExceptionHandler { @ExceptionHandler @ResponseBody @ResponseStatus(HttpStatus.OK) public ResultDto globalException(HttpServletResponse response, Exception ex){ log.info("ExceptionHandler..."); log.info("错误代码:" + response.getStatus()); ResultDto resultDto = new ResultDto(); resultDto.setCode(0); resultDto.setMsg(ex.getMessage()); resultDto.setData(null); return resultDto; }}
定义个返回到前端的通用构造体
@Datapublic class ResultDto { //申请后果0示意失败,其余是胜利 private int code; //失败的音讯 private String msg; //理论返回到前端的数据 private Object data;}
而后咱们写一个controller模仿抛出异样
@GetMapping("test1")public String test1() throws Exception{ if(true){ throw new NullPointerException("NullPointerException"); } return "ok";}@GetMapping("test2")public String test2() throws Exception{ if(true){ throw new RuntimeException("RuntimeException"); } return "ok";}@GetMapping("test3")public String test3() throws MyException{ if(true){ //不能间接拋Exception 否则不能捕捉,能够本人定义一个异样 throw new MyException("MyException"); } return "ok";}
申请下,看看postman返回的是什么
{ "code": 0, "msg": "NullPointerException", "data": null}
在理论业务中咱们通常返回自定义的异样,那么我接下来定义一个本人的异样,并对本人的异样进行独自的解决:
public class MyException extends Exception { public MyException() { super(); } public MyException(String message) { super(message); } public MyException(String message, Throwable cause) { super(message, cause); } public MyException(Throwable cause) { super(cause); } protected MyException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); }}
而后在GlobalExceptionHandler中减少对MyException的解决:
@ExceptionHandler(MyException.class)@ResponseBody@ResponseStatus(HttpStatus.OK)public ResultDto myException(HttpServletResponse response, MyException ex){ log.info("MyExceptionHandler..."); log.info("错误代码:" + response.getStatus()); ResultDto resultDto = new ResultDto(); resultDto.setCode(0); resultDto.setMsg(ex.getMessage()); resultDto.setData(null); return resultDto;}
申请http://localhost:8080/test3
看看输入到前端的是什么
{ "code": 0, "msg": "MyException", "data": null}
这里其实看不出来到底走的是myException还是globalException然而如果你看后盾日志输入就能清晰的看到。因而咱们在对多种异样进行解决的时候springboot会优先解决子类异样。
更多java原创浏览:https://javawu.com