如果返回类型是list,那么如何在spring boot的getmapping中返回字符串


@GetMapping("/library/book/{genre}")
private List<Library> getBookByGenre(@PathVariable("genre") String genre) {
if (libraryService.getBookByGenre(genre).isEmpty()) {
return ;
} else {
return libraryService.getBookByGenre(genre);
}
}

这是我的控制器代码。当没有特定类型的数据时,它返回一个空列表,但我想返回一个字符串,显示"没有找到此类型的数据";在邮递员。

"trace": "org.springframework.web.client.HttpClientErrorException$NotFound: 404 : [{"errorCode":404,"errorMessage":"No data found for this genre"}]rntat org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:113)rntat org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:186)rntat org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:125)rntat org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)rntat org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:819)rntat org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:777)rntat org.springframework.web.client.RestTemplate.execute(RestTemplate.java:711)rntat org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:602)rntat com.example.student.adapter.outbound.Repository.getBookbyGenre(Repository.java:64)rntat com.example.student.adapter.outbound.Repository$$FastClassBySpringCGLIB$$c14fd765.invoke(<generated>)rntat org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)rntat org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:779)rntat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)rntat org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:750)rntat org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137)rntat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)rntat org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:750)rntat org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:692)rntat com.example.student.adapter.outbound.Repository$$EnhancerBySpringCGLIB$$c8c38c72.getBookbyGenre(<generated>)rntat com.example.student.core.service.StudentService.getBookbyGenre(StudentService.java:43)rntat com.example.student.adapter.inbound.StudentController.getBookbyGenre(StudentController.java:30)rntat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)rntat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)rntat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)rntat java.lang.reflect.Method.invoke(Method.java:498)rntat org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)rntat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)rntat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)rntat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)rntat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)rntat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)rntat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)rntat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)rntat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)rntat org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)rntat javax.servlet.http.HttpServlet.service(HttpServlet.java:655)rntat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)rntat javax.servlet.http.HttpServlet.service(HttpServlet.java:764)rntat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)rntat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)rntat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)rntat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)rntat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)rntat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)rntat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)rntat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)rntat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)rntat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)rntat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)rntat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)rntat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)rntat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)rntat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)rntat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)rntat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)rntat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)rntat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)rntat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)rntat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)rntat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)rntat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)rntat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)rntat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)rntat org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)rntat org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893)rntat org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1726)rntat org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)rntat org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)rntat org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)rntat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)rntat java.lang.Thread.run(Thread.java:748)rn",
"message": "404 : [{"errorCode":404,"errorMessage":"No data found for this genre"}]",
"path": "/Student/library/genre/lol"

最好的选择是抛出一个自定义异常:

@ResponseStatus(HttpStatus.NOT_FOUND)
public class NoBooksFoundException extends RuntimeException {
private static final String ERROR_MESSAGE = "No data found for this genre";
public NoBooksFoundException() {
super(ERROR_MESSAGE);
}
}
@GetMapping("/library/book/{genre}")
private List<Library> getBookByGenre(@PathVariable("genre") String genre) {
if (libraryService.getBookByGenre(genre).isEmpty()) {
throw NoBooksFoundException();
} else {
return libraryService.getBookByGenre(genre);
}
}

然后你会有一个全局异常处理程序来处理它:

@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = {NoBooksFoundException.class})
public ResponseEntity<Object> handleCustomExceptions(Exception exception, WebRequest webRequest) {
HttpStatus errorCode = this.resolveAnnotatedResponseStatus(exception);
return this.handleExceptionInternal(exception, new ErrorInfo(errorCode.value(), exception.getMessage()), new HttpHeaders(), errorCode, webRequest);
}
private HttpStatus resolveAnnotatedResponseStatus(Exception exception) {
ResponseStatus annotation = findMergedAnnotation(exception.getClass(), ResponseStatus.class);
return Objects.nonNull(annotation) ? annotation.value() : HttpStatus.INTERNAL_SERVER_ERROR;
}
}

ErrorInfo如下:

public class ErrorInfo {
private final int errorCode;
private final String errorMessage;
// getters, setters, constructor
}

相关内容

  • 没有找到相关文章

最新更新