Springboot2.0中如何处理自定义异常并返回json(json,springboot,编程语言)

时间:2024-05-05 12:57:15 作者 : 石家庄SEO 分类 : 编程语言
  • TAG :

1. 编写自定义异常类

packagecn.jfjb.crud.exception;publicclassUserNotExistExceptionextendsRuntimeException{publicUserNotExistException(){super("用户不存在");}}

2. 处理自测试异常

packagecn.jfjb.crud.handler;importcn.jfjb.crud.exception.UserNotExistException;importorg.springframework.web.bind.annotation.ControllerAdvice;importorg.springframework.web.bind.annotation.ExceptionHandler;importorg.springframework.web.bind.annotation.ResponseBody;importjava.util.HashMap;importjava.util.Map;@ControllerAdvicepublicclassMyExceptionHandler{@ResponseBody@ExceptionHandler(UserNotExistException.class)publicMap<String,Object>handleException(Exceptione){Map<String,Object>map=newHashMap<>();map.put("code","user.notexist");map.put("message",e.getMessage());returnmap;}}

3. 配置application.yml文件(不配置的话无法获取exception)

server:error:include-exception:true

4. 编写测试

packagecn.jfjb.crud.controller;importcn.jfjb.crud.exception.UserNotExistException;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestParam;@ControllerpublicclassHelloController{@RequestMapping({"/testException"})publicStringtestException(@RequestParam("user")Stringuser){if(user!="aaa"){thrownewUserNotExistException();}return"index";}}

Springboot2.0中如何处理自定义异常并返回json

Springboot2.0中如何处理自定义异常并返回json

 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:Springboot2.0中如何处理自定义异常并返回json的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:web开发中怎么实现代码可读性下一篇:

5 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18