| 
                         使用 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" 
 - } 
 
                          (编辑:泰州站长网) 
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! 
                     |