行使 Get 哀求 localhost:8080/api/resourceNotFoundException[1] (curl -i -s -X GET url),处事端返回的 JSON 数据如下:
- {
- "message": "Sorry, the resourse not found!",
- "errorTypeName": "com.twuc.webApp.exception.ResourceNotFoundException"
- }
5. 编写测试类
MockMvc 由org.springframework.boot.test包提供,实现了对Http哀求的模仿,一样平常用于我们测试 controller 层。
- /**
- * @author shuang.kou
- */
- @AutoConfigureMockMvc
- @SpringBootTest
- public class ExceptionTest {
- @Autowired
- MockMvc mockMvc;
- @Test
- void should_return_400_if_param_not_valid() throws Exception {
- mockMvc.perform(get("/api/illegalArgumentException"))
- .andExpect(status().is(400))
- .andExpect(jsonPath("$.message").value("参数错误!"));
- }
- @Test
- void should_return_404_if_resourse_not_found() throws Exception {
- mockMvc.perform(get("/api/resourceNotFoundException"))
- .andExpect(status().is(404))
- .andExpect(jsonPath("$.message").value("Sorry, the resourse not found!"));
- }
- }
二、 @ExceptionHandler 处理赏罚 Controller 级此外非常
我们方才也说了行使@ControllerAdvice注解 可以通过 assignableTypes指定特定的类,让非常处理赏罚类只处理赏罚特定类抛出的非常。以是这种处理赏罚非常的方法,现实上此刻行使的较量少了。
我们把下面这段代码移到 src/main/java/com/twuc/webApp/exception/GlobalExceptionHandler.java 中就可以了。
- @ExceptionHandler(value = Exception.class)// 拦截全部非常
- public ResponseEntity<ErrorResponse> exceptionHandler(Exception e) {
- if (e instanceof IllegalArgumentException) {
- return ResponseEntity.status(400).body(illegalArgumentResponse);
- } else if (e instanceof ResourceNotFoundException) {
- return ResponseEntity.status(404).body(resourseNotFoundResponse);
- }
- return null;
- }
三、 ResponseStatusException
研究 ResponseStatusException 我们先来看看,通过 ResponseStatus注解简朴处理赏罚非常的要领(将非常映射为状态码)。
src/main/java/com/twuc/webApp/exception/ResourceNotFoundException.java
- @ResponseStatus(code = HttpStatus.NOT_FOUND)
- public class ResourseNotFoundException2 extends RuntimeException {
- public ResourseNotFoundException2() {
- }
- public ResourseNotFoundException2(String message) {
- super(message);
- }
- }
src/main/java/com/twuc/webApp/web/ResponseStatusExceptionController.java
- @RestController
- @RequestMapping("/api")
- public class ResponseStatusExceptionController {
- @GetMapping("/resourceNotFoundException2")
- public void throwException3() {
- throw new ResourseNotFoundException2("Sorry, the resourse not found!");
- }
- }
行使 Get 哀求 localhost:8080/api/resourceNotFoundException2[2] ,处事端返回的 JSON 数据如下:
- {
- "timestamp": "2019-08-21T07:11:43.744+0000",
- "status": 404,
- "error": "Not Found",
- "message": "Sorry, the resourse not found!",
- "path": "/api/resourceNotFoundException2"
- }
(编辑:湖南网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|