Spring Boot REST Service未在JSON输出中显示@ResponseStatus异常原因

时间:2014-10-27 10:18:59

标签: spring spring-mvc spring-boot

我创建了一个带有@ResponseStatus注释的异常,允许抛出异常并从前端的JSON内容中接收原因。

@ResponseStatus(value = BAD_REQUEST,  reason='exception.user.exists')
class UserAlreadyExists extends RuntimeException{
}

当我尝试在服务中按键解析消息时,我收到了本地化消息。

@Service
public class UserService implements UserDetailsService {

    @Autowired
    private MessageSource messageSource

    private void verifyIsNewUser(User user) {
    if (userRepository.countByEmail(user.email)) {
        def reason = this.messageSource.getMessage("exception.user.exists", null, "just a message", LocaleContextHolder.getLocale()); 
        println reason // User already registered
        throw new UserAlreadyExists()
    }
}

问题1

现在,如果我调试ResponseStatusExceptionResolver,我发现MessageSource是 null ,这很奇怪。当ResponseStatusExceptionResolver正在实现接口MessageSourceAware时,它应该注入一个messageSource。为什么不呢?

问题2

如果我忽略了我没有自定义消息并查看到达前端的JSON输出这一事实,我面临以下结果:

{"timestamp":1414403066197,"status":400,"error":"Bad Request","exception":"io.test.UserAlreadyExists","message":null,"path":"/register/"}

我希望在JSON响应中看到没有关于文本字段的内容。类似于{...,"reason":"exception.user.exists","message":null, ....}

为什么JSON响应不包含原因(键)?查看ResponseStatusExceptionResolver的代码时,如果没有检索到密钥消息,则只使用密钥/消息。

1 个答案:

答案 0 :(得分:0)

答案1:Spring IMO中的一个错误。 ResponseStatusExceptionResolver不是@Bean,因此不会注入MessageSource

答案2:Spring Boot的功能请求。您正在看到Boot的默认/错误输出,它会在Exception中查找消息,而不是HttpServletResponse"原因"代码(我假设可以通过API获得)。这是一个链接:https://github.com/spring-projects/spring-boot/issues/1762