gpt4 book ai didi

java - @ControllerAdvice 不映射到错误

转载 作者:太空宇宙 更新时间:2023-11-04 09:23:01 25 4
gpt4 key购买 nike

我有一个 REST 服务,我需要使用自定义 json 响应发送适当的状态代码,这解释了错误的原因。

我有@Controller类,它公开了一个服务/test,在访问该服务时,我抛出了一个自定义异常(扩展了Exception类)

我有一个处理异常的 @ControllerAdvice 类。但是,每当我收到错误时,我都不会收到 json 响应,而是打印堆栈跟踪。

检查了博客并尝试了解决方案。但无法解决。

@ControllerAdvice(basePackages = "com.test")
public class ResponseExceptionHandler extends ResponseEntityExceptionHandler{


@ExceptionHandler(value= {MyException.class})
@ResponseStatus(code=HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
ResponseEntity<MyResponse> commonServiceException(MyException ex) {
MyResponse errors = new MyResponse();

errors.setTimeStamp(LocalDateTime.now());
errors.setErrorCode(ex.getErrorCode());
errors.setErrorMessage(ex.getMessage());
errors.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
errors.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
return new ResponseEntity<>(errors, HttpStatus.INTERNAL_SERVER_ERROR);
}
}

服务

@Controller
....
public class test{
..
@GET
@Path("/test")
//@ExceptionHandler(value= {MyException.class})
@Produces(MediaType.APPLICATION_JSON)
public String test() throws MyException{
throw new MyException("123", "message");

}

上下文.xml

<context:component-scan base-package=" com.test">
<context:include-filter type="annotation"
expression="org.springframework.web.bind.annotation.ControllerAdvice" />
</context:component-scan>

预期:JSON 响应

实际:类型异常报告

消息服务当前不可用。错误代码:应用程序错误。错误

描述服务器遇到意外情况,无法满足请求。

异常

com.test.MyException:服务当前不可用。错误代码:应用程序错误................................................

最佳答案

这是因为我混淆了 Jersey 和 Spring 框架。在 web.xml 中进行必要的 spring servlet 配置并使用 @RequestMapping 后,问题得到解决。

关于java - @ControllerAdvice 不映射到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58077947/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com