【发布时间】: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