spring boot项目从零开始-(6)统一处理异常

àì夳堔傛蜴生んèń 2023-07-01 13:54 78阅读 0赞

spring boot项目从零开始-统一处理异常

  • 简述
      • 前提
      • 目录
  • 步骤
      • 自定义异常类ControllerException\ServiceException
      • 结果类Result
      • 拦截报错类
  • 测试

简述

前提

目录

在这里插入图片描述

步骤

关键:@ControllerAdvice + @ExceptionHandler

自定义异常类ControllerException\ServiceException

  1. package com.ydfind.start.common.exception;
  2. /**
  3. * controller异常
  4. * @author ydfind
  5. * @date 2019.1.22
  6. */
  7. public class ControllerException extends RuntimeException {
  8. public ControllerException(String message) {
  9. super(message);
  10. }
  11. public ControllerException(String message, Throwable cause) {
  12. super(message, cause);
  13. }
  14. }
  15. package com.ydfind.start.common.exception;
  16. /**
  17. * service异常
  18. * @author ydfind
  19. * @date 2019.1.22
  20. */
  21. public class ServiceException extends RuntimeException {
  22. public ServiceException(String message) {
  23. super(message);
  24. }
  25. public ServiceException(String message, Throwable cause) {
  26. super(message, cause);
  27. }
  28. }

结果类Result

  1. package com.ydfind.start.common.response;
  2. import lombok.Data;
  3. import java.io.Serializable;
  4. /**
  5. * 请求结果
  6. * @param <T> 参数data类
  7. * @author ydifnd
  8. * @date 2019.1.22
  9. */
  10. @Data
  11. public class Result<T> implements Serializable {
  12. public static String SUCCESS = "200";
  13. public static String ERROR = "500";
  14. private T data;
  15. private String code;
  16. private String msg;
  17. public Result(String code, String msg, T data) {
  18. this.code = code;
  19. this.msg = msg;
  20. this.data = data;
  21. }
  22. public static <T> Result<T> success(String msg, T data) {
  23. return new Result<>(SUCCESS, msg, data);
  24. }
  25. public static <T> Result<T> error(String msg, T data) {
  26. return new Result<>(ERROR, msg, data);
  27. }
  28. }

拦截报错类

  1. package com.ydfind.start.common.handler;
  2. import com.ydfind.start.common.exception.ControllerException;
  3. import com.ydfind.start.common.exception.ServiceException;
  4. import com.ydfind.start.common.response.Result;
  5. import lombok.extern.slf4j.Slf4j;
  6. import org.springframework.web.bind.annotation.ControllerAdvice;
  7. import org.springframework.web.bind.annotation.ExceptionHandler;
  8. import org.springframework.web.bind.annotation.ResponseBody;
  9. /**
  10. * 统一拦截报错
  11. * @author ydfind
  12. * @date 2020.1.22
  13. */
  14. @Slf4j
  15. @ControllerAdvice
  16. public class ResultHandler {
  17. @ResponseBody
  18. @ExceptionHandler
  19. public Object handleException(Exception e) {
  20. if (!(e instanceof ServiceException) && !(e instanceof ControllerException)) {
  21. log.error(e.getMessage(), e);
  22. }
  23. return Result.error(e.getMessage(), null);
  24. }
  25. }

测试

  1. @Autowired
  2. MyMockService myMockService;
  3. @GetMapping("/name")
  4. @ApiOperation("获取名称")
  5. @ApiImplicitParam(name = "id", value = "主键id", defaultValue = "0")
  6. public Result<String> getName(String id) {
  7. return Result.success(null, myMockService.getName(id));
  8. }
  9. @GetMapping("/expression")
  10. public Result<String> expression() {
  11. if (true) {
  12. throw new ControllerException("expression");
  13. }
  14. return Result.success(null, "expression");
  15. }
  16. package com.ydfind.start.controller.test;
  17. import com.alibaba.fastjson.JSONObject;
  18. import com.ydfind.start.BaseTest;
  19. import com.ydfind.start.common.exception.ControllerException;
  20. import com.ydfind.start.common.exception.ServiceException;
  21. import com.ydfind.start.common.response.Result;
  22. import com.ydfind.start.service.test.MyMockService;
  23. import org.junit.Before;
  24. import org.junit.Test;
  25. import org.mockito.Mockito;
  26. import org.springframework.beans.factory.annotation.Autowired;
  27. import org.springframework.boot.test.mock.mockito.MockBean;
  28. import org.springframework.http.MediaType;
  29. import org.springframework.test.web.servlet.MockMvc;
  30. import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
  31. import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
  32. import org.springframework.test.web.servlet.setup.MockMvcBuilders;
  33. import org.springframework.web.context.WebApplicationContext;
  34. public class ExceptionTest extends BaseTest {
  35. @Autowired
  36. private WebApplicationContext webApplicationContext;
  37. private MockMvc mockMvc;
  38. @MockBean
  39. private MyMockService myMockService;
  40. @Before
  41. public void init() {
  42. mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
  43. }
  44. @Test
  45. public void testGet() throws Exception {
  46. String returnString = "this is mockito name.";
  47. Mockito.doReturn(returnString).when(myMockService).getName(Mockito.anyString());
  48. String resultStr = mockMvc.perform(MockMvcRequestBuilders.get("/mock/name")
  49. .param("id", "user")
  50. .contentType(MediaType.APPLICATION_JSON_UTF8))
  51. .andExpect(MockMvcResultMatchers.status().isOk())
  52. .andReturn().getResponse().getContentAsString();
  53. Result<String> result = JSONObject.parseObject(resultStr, Result.class);
  54. assertSuccess(result, returnString);
  55. String exceptionStr = "Service exception";
  56. Mockito.doThrow(new ServiceException(exceptionStr)).when(myMockService).getName(Mockito.anyString());
  57. resultStr = mockMvc.perform(MockMvcRequestBuilders.get("/mock/name")
  58. .param("id", "user")
  59. .contentType(MediaType.APPLICATION_JSON_UTF8))
  60. .andExpect(MockMvcResultMatchers.status().isOk())
  61. .andReturn().getResponse().getContentAsString();
  62. result = JSONObject.parseObject(resultStr, Result.class);
  63. assertFail(result, exceptionStr);
  64. exceptionStr = "Controller exception";
  65. Mockito.doThrow(new ControllerException(exceptionStr)).when(myMockService).getName(Mockito.anyString());
  66. resultStr = mockMvc.perform(MockMvcRequestBuilders.get("/mock/name")
  67. .param("id", "user")
  68. .contentType(MediaType.APPLICATION_JSON_UTF8))
  69. .andExpect(MockMvcResultMatchers.status().isOk())
  70. .andReturn().getResponse().getContentAsString();
  71. result = JSONObject.parseObject(resultStr, Result.class);
  72. assertFail(result, exceptionStr);
  73. exceptionStr = "RuntimeException";
  74. Mockito.doThrow(new RuntimeException(exceptionStr)).when(myMockService).getName(Mockito.anyString());
  75. resultStr = mockMvc.perform(MockMvcRequestBuilders.get("/mock/name")
  76. .param("id", "user")
  77. .contentType(MediaType.APPLICATION_JSON_UTF8))
  78. .andExpect(MockMvcResultMatchers.status().isOk())
  79. .andReturn().getResponse().getContentAsString();
  80. result = JSONObject.parseObject(resultStr, Result.class);
  81. assertFail(result, exceptionStr);
  82. }
  83. @Test
  84. public void testExpression() throws Exception {
  85. String resultStr = mockMvc.perform(MockMvcRequestBuilders.get("/expression")
  86. .contentType(MediaType.APPLICATION_JSON_UTF8))
  87. .andExpect(MockMvcResultMatchers.status().isOk())
  88. .andReturn().getResponse().getContentAsString();
  89. Result<String> result = JSONObject.parseObject(resultStr, Result.class);
  90. assertFail(result, "expression");
  91. }
  92. }

发表评论

表情:
评论列表 (有 0 条评论,78人围观)

还没有评论,来说两句吧...

相关阅读