Java服务捕获异常仍返回500,如何自定义错误消息替代?
解决方案
问题出在你的try-catch块范围太窄,只包裹了testRequestRepository.save()的逻辑,但前面的JSON解析、字段获取代码都在try块之外,这些步骤抛出的异常不会被捕获,直接导致500错误。
比如这两行代码:
JSONObject json = new JSONObject(data); boolean hasHealthInsurance = json.getAsString("hasHealthInsurance").equals("true");
如果data里缺少hasHealthInsurance这个key,json.getAsString()会抛出JSONException;如果返回值是null,调用equals("true")会抛出NullPointerException——这些异常都不在try块的覆盖范围内,自然会触发服务器500错误。
修正后的代码
把所有可能抛出异常的操作都放进try块中:
public String storeTestRequest(Map<String, String> data, HttpSession session) { try { JSONObject json = new JSONObject(data); boolean hasHealthInsurance = json.getAsString("hasHealthInsurance").equals("true"); this.testRequestRepository.save(new TestRequest( json.getAsString("firstname"), json.getAsString("surname"), json.getAsString("street"), hasHealthInsurance )); return "All good."; } catch (Exception e) { // 可添加日志打印,方便后台排查具体异常原因 // e.printStackTrace(); return "Something went wrong."; } }
额外说明
- 若使用
org.json.JSONObject,getAsString()在key不存在时会直接抛出JSONException,即便你不想做字段校验,也必须把这部分逻辑纳入异常捕获范围。 - 在catch块中添加日志输出,既能返回统一的用户提示,又能在后台定位具体问题,便于后续维护。
内容的提问来源于stack exchange,提问作者Reem
相关产品推荐
相关产品推荐

