spring 如何为Sping Boot 项目将自定义异常处理响应消息修剪为更短的消息?[已关闭]

2w2cym1i  于 2022-10-31  发布在  Spring
关注(0)|答案(2)|浏览(75)

已关闭。此问题需要details or clarity。当前不接受答案。
**想要改进此问题吗?**通过editing this post添加详细信息并阐明问题。

16天前关闭。
Improve this question
当我运行我的应用程序时,在Postman中给出正确的数据后,我得到了如下所示的结果。

{
 "sportsId":"1000",
 "noOfPlayers":"22",
 "sportsName":"Hockey",
 "sportsType":"Outdoor"
}

回应

{
 "sportsId":"1000",
 "sportsName":"Hockey",
 "sportsType":"Outdoor"
}

在处理任何异常的情况下,比如输入相同的数据,这将是自定义异常处理的响应。

{
 "timestamp": "2022-10-13T18:44:27.911+00:00",
"status": 500,
"error": "Internal Server Error",
"trace": "com.cognizant.sportseventmanagement.exception.SportInsertionException: Sport already Exist!\r\n\tat com.cognizant.sportseventmanagement.service.SportsEventService.lambda$addSport$0(SportsEventService.java:34)\r\n\tat java.base/java.util.Optional.ifPresent(Optional.java:178)\r\n\tat com.cognizant.sportseventmanagement.service.SportsEventService.addSport(SportsEventService.java:33)\r\n\tat com.cognizant.sportseventmanagement.controller.SportsEventController.addSport(SportsEventController.java:66)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:568)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)\r\n\tat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)\r\n\tat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)\r\n\tat org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)\r\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:681)\r\n\tat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)\r\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:764)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)\r\n\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)\r\n\tat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)\r\n\tat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)\r\n\tat org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:96)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)\r\n\tat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)\r\n\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)\r\n\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)\r\n\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)\r\n\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)\r\n\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)\r\n\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)\r\n\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360)\r\n\tat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)\r\n\tat org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)\r\n\tat org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:890)\r\n\tat org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1787)\r\n\tat org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)\r\n\tat org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)\r\n\tat org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)\r\n\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\r\n\tat java.base/java.lang.Thread.run(Thread.java:833)\r\n",
"message": "Sport already Exist!",
"path": "/api/v1/sportsEvent/addSport"
}

但我希望回应是这样的

{
  "status":500,
  "message":"Sport already Exist!"
}

有人能帮我什么所有的变化,我需要经历,使我可以简单地我的React?

z18hc3ub

z18hc3ub1#

在您的异常包中,添加一个扩展到响应实体异常处理程序的 * RestResponseEntityException Handler.java* 类。
使用@ExceptionalHandler(Class_to_be_handeled.java) @ResponseBody @ResponseStatus(HttpStatus.NOT_FOUND)注解来注解类别。
最后,创建一个ExceptionMessage.java类来处理响应。
请查看以下代码以了解进一步的说明。

静态响应实体异常处理程序.java

@ControllerAdvice
public class RestResponseEntityExceptionHandler extends 
ResponseEntityExceptionHandler {

@ExceptionHandler(Class_to_be_handeled.class)
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ExceptionMessage sportInsertionExceptionHandler(SportInsertionException 
exception)
{
    ExceptionMessage message = new ExceptionMessage(HttpStatus.BAD_REQUEST, 
    exception.getMessage());

    return message;
}
}

异常消息.java

public class ExceptionMessage {

private HttpStatus httpStatus;
private String msg;

public ExceptionMessage() {
}

public ExceptionMessage(HttpStatus httpStatus, String msg) {
    this.httpStatus = httpStatus;
    this.msg = msg;
}

public HttpStatus getHttpStatus() {
    return httpStatus;
}

public void setHttpStatus(HttpStatus httpStatus) {
    this.httpStatus = httpStatus;
}

public String getMsg() {
    return msg;
}

public void setMsg(String msg) {
    this.msg = msg;
}
}

最终答复

{
 "httpStatus": "BAD_REQUEST",
 "msg": "Sport already Exist!"
}

希望这是有帮助的!
你随时都可以给我打电话。

ryevplcw

ryevplcw2#

您可以返回一个HttpStatus.INTERNAL_SERVER_ERROR,并在正文中包含一条消息,请查看下面代码。

@RequestMapping("/insert")
    public ResponseEntity<Object> insertData(HttpServletRequest request){
        if ( checkDuplicateData(request) ) {
        throw new DuplicateDataApiException();
     } else{
        return new ResponseEntity.ok("Data Inserted successfully");
     } 
    }

说明:它将检查数据是否重复,然后抛出服务器异常,否则需要响应ok/200
@此处为异常处理程序代码

@ExceptionHandler(value = DuplicateDataApiException.class)
    public ResponseEntity<Object> duplicateDataApiException(DuplicateDataApiException exception){
        return new ResponseEntity<>("Duplicate Data Error", HttpStatus.INTERNAL_SERVER_ERROR);
    }

我希望,它能帮上忙!

相关问题