我使用spring boot并开始管理错误。
我创建了一个异常处理来处理未找到的资源。
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
private ResponseEntity<Void> handleResourceNotFoundException(ResourceNotFoundException e) {
return ResponseEntity.notFound().build();
}
}
在我的控制器中我做了
@RequestMapping(value = "/members/{memberId}", method = RequestMethod.GET)
public ResponseEntity getMemberById(@PathVariable("memberId") Long memberId) throws ResourceNotFoundException {
MemberDto memberDto = memberService.getMemberById(memberId);
return new ResponseEntity(memberDto, HttpStatus.OK);
}
@Override
public MemberDto getMemberById(Long memberId) throws ResourceNotFoundException {
Member member = memberRepository.findOne(memberId);
if (member == null) {
throw new ResourceNotFoundException("Member not found");
}
return convertToMemberDto(member);
}
我只有几个成员,所以如果我打电话
本地主机:/构件/ 999
我在响应标题中看到chrome
HTTP/1.1 404 Not Found
Server: Apache-Coyote/1.1
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Length: 0
Date: Tue, 19 Jul 2016 01:04:25 GMT
为什么我没有收到消息:找不到会员? 这是使用spring boot管理错误的好方法吗? 如何在控制器中管理不同类型的错误?
答案 0 :(得分:0)
您需要更改异常处理程序以返回包含您要返回的错误消息的正文,即:
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
private ResponseEntity<Void> handleResourceNotFoundException(ResourceNotFoundException e) {
// log exception
return ResponseEntity
.status(HttpStatus.FORBIDDEN)
.body("Member not found");
}
}