英文:
How to handle wrong PathVariable
问题
我有一个端点:
@GetMapping("/student/{id}")
public Student getStudentByID(@PathVariable Long id)
如何处理这种情况:/student/aaa
当用户传递的不是Long
类型的值时。现在我收到了400错误请求和空JSON作为上述请求的响应。
英文:
I have endpoint :
@GetMapping("/student/{id})
public Student getStudentByID(@PathVariable Long id)
How to handle the situation: /student/aaa
When the user passes something else than Long
. Now I have received 400 Bad Request and Empty JSON for the above request.
答案1
得分: 1
为了控制错误处理,您可以接受一个字符串参数,并在转换为长整型失败时捕获异常。
public Student getStudentByID(@PathVariable String idString) {
try {
Long id = Long.valueOf(idString);
} catch (NumberFormatException e) {
// 处理非长整型值
}
}
英文:
To control your error handling, you can accept String parameter and catch Exception if failed to convert to long
public Student getStudentByID(@PathVariable String idString) {
try {
Long id = Long.valueOf(idString);
} catch(NumberFormatException e) {
// handle non long value
}
答案2
得分: 1
400状态码是根据您的编码而来的良好响应。
请参考以下示例:
以下API将接受整数。示例:student/123
。
@GetMapping("/student/{id}")
public Student getStudentByID(@PathVariable Long id)
以下API将接受字符串。示例:/student/aaa
@GetMapping("/student/{id}")
public Student getStudentByID(@PathVariable String id)
如果您想要添加验证,请使用以下代码:
@GetMapping("/student/{id}")
public ResponseEntity<Student> getStudentByID(@PathVariable String id) {
try {
Long id = Long.valueOf(id);
} catch(NumberFormatException e) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(new Student());
}
小建议,始终在您的服务中使用ResponseEntity。这样您就可以控制/返回状态码。参考:https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/ResponseEntity.html
英文:
400 Status code is a good response as per your coding.
See the below examples:
Below api will accept the integer. example student/123
.
@GetMapping("/student/{id}")
public Student getStudentByID(@PathVariable Long id)
Below api will accept the string. example /student/aaa
@GetMapping("/student/{id}")
public Student getStudentByID(@PathVariable String id)
If you want add validation use the below code:
@GetMapping("/student/{id}")
public ResponseEntity<Student> getStudentByID(@PathVariable String id) {
try {
Long id = Long.valueOf(id);
} catch(NumberFormatException e) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(new Student());
}
Small Advice, always use the, ResponseEntity in your services. So you can control/return the status code. Reference: https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/ResponseEntity.html
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论