1.自定义异常
public class MyException extends RuntimeException{ public MyException(String message) { super(message); } } @ResponseStatus(HttpStatus.NOT_FOUND) public class MyNotFoundException extends MyException { public MyNotFoundException(String content,Object keyword) { super(String.join(": ","找不到"+content+",关键字", keyword.toString())); } }
2.异常处理
@ControllerAdvice public class ExceptionHandlerAdvice { /******************************************* * 自定义异常处理 *************************************************/ @ExceptionHandler(MyException.class) ResponseEntitymyExceptionHandle(MyException e) { HttpStatus responseStatus = resolveAnnotatedResponseStatus(e); MyExceptionRepresentationbody = new MyExceptionRepresentation(e, responseStatus); return new ResponseEntity<>(body, responseStatus); } /******************************************* * 其他已知异常,消息定制化处理 ************************************************/ @ExceptionHandler(MethodArgumentTypeMismatchException.class) ResponseEntity methodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) { String message = String.join("参数的错误输入: ", e.getName(), e.getValue().toString()); MyExceptionRepresentation body = new MyExceptionRepresentation(e,message, HttpStatus.BAD_REQUEST); return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST); } ///解析状态码 public static HttpStatus resolveAnnotatedResponseStatus(Exception exception) { ResponseStatus annotation = findMergedAnnotation(exception.getClass(), ResponseStatus.class); if (annotation != null) { return annotation.value(); } return HttpStatus.INTERNAL_SERVER_ERROR; } } @Data class MyExceptionRepresentation { private boolean myException= true; private Date timestamp; private int status; private String error; private String exception; private String message; private String path; public MyExceptionRepresentation(Exception e, HttpStatus responseStatus) { this(e, e.getLocalizedMessage(),responseStatus); } public MyExceptionRepresentation(Exception e, String message, HttpStatus responseStatus) { this.timestamp = new Date(); this.status = responseStatus.value(); this.error = responseStatus.getReasonPhrase(); this.exception = e.getClass().getName(); this.message = message; HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); this.path = request.getServletPath(); } }
3.RestTempldate处理异常
public class MyErrorHandler implements ResponseErrorHandler { @Override public void handleError(ClientHttpResponse response) throws IOException { String e = CharStreams.toString(new InputStreamReader(response.getBody())); JSONObject exception = JSONObject.fromObject(e); boolean myException = (boolean) exception.getOrDefault("myException", false); if (myException) { throw new RuntimeException((String) exception.get("message")); } else { throw new RuntimeException(exception.toString()); } } } public class RestTemplateTest { RestTemplate restTemplate; @Before public void setUp(){ restTemplate = new RestTemplate(); restTemplate.setErrorHandler(new MyErrorHandler()); } @Test public void testSuccessAndMyException() { // String url = "http://localhost:9124/course/list/试用期"; String url = "http://localhost:9124/course/list/试用"; try { Arrays.stream(restTemplate.getForObject(url, Course[].class)) .map(Course::getName) .forEach(System.out::println); } catch (MyException e) { System.out.println(e.getMessage()); System.out.println(e.getExceptionName()); } } }