【问题标题】:Spring Can't recognise application.proerties file. Unable to display the configuration defines in property fileSpring 无法识别 application.properties 文件。无法显示属性文件中的配置定义
【发布时间】:2021-07-25 01:55:51
【问题描述】:

我正在尝试在处理异常时显示我的自定义消息。但是我在邮递员中没有得到任何回应。这是我用过的代码sn-p

所以,这是我的控制器类方法

@GetMapping(value="/customers/{customerId}")
public ResponseEntity<Customer> getCustomerById(@PathVariable Integer customerId) throws Exception
{
    try {
    Customer customer = customerService.getCustomer(customerId);    
    ResponseEntity<Customer> response = new ResponseEntity<Customer>(customer, HttpStatus.OK);
    return response;
    }
    catch(Exception e)
    {
        throw new ResponseStatusException(HttpStatus.NOT_FOUND,environment.getProperty(e.getMessage()),e);
    }
}

这是我从 getCustomerById 方法调用的服务层方法 -

@Service(value = "CustomerService")

公共类 CustomerServiceImpl 实现 CustomerService {

@Autowired
private CustomerDao customerDao;

@Override
public Customer getCustomer(Integer customerId) throws Exception {
    Customer customer = customerDao.getCustomer(customerId);
    if (customer == null) {
        throw new Exception("Service.CUSTOMER_UNAVAILABLE");
    }
    return customer;
}

这是我的属性文件

server.port=3557

Service.CUSTOMER_ALREADY_EXIST=客户已经存在。添加具有不同属性的客户。 Service.CUSTOMER_UNAVAILABLE=未找到客户详细信息。提供有效的客户详细信息。

邮递员回应 -

{
"timestamp": "2021-05-02T10:21:22.455+00:00",
"status": 500,
"error": "Internal Server Error",
"message": "",
"path": "/DemoBank/customers/8"

}

【问题讨论】:

  • 缺少属性与 500 响应有什么关系? 500 表示服务器响应您的请求期间发生的内部错误。有些东西抛出异常 - 你只需要调试
  • 我想要显示我在服务层和属性文件中定义的自定义异常 Service.CUSTOMER_ALREADY_EXIST=客户已经存在。添加具有不同属性的客户。 & Service.CUSTOMER_UNAVAILABLE=未找到客户详细信息。提供有效的客户详细信息。

标签: spring spring-mvc exception spring-rest


【解决方案1】:

那是因为您抛出异常而不是返回您的自定义响应。 Spring 的异常总是返回 500。

改变这一行:

throw new ResponseStatusException(HttpStatus.NOT_FOUND,environment.getProperty(e.getMessage()),e);

到这里:

return new ResponseEntity<>(environment.getProperty(e.getMessage()), HttpStatus.NOT_FOUND);

【讨论】:

    猜你喜欢
    • 2017-10-04
    • 1970-01-01
    • 2015-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-31
    • 2017-12-14
    • 2022-06-28
    相关资源
    最近更新 更多