Handle ResourceNotFoundException, message not good

spring spring-boot

1433 просмотра

1 ответ

61 Репутация автора

I use spring boot and I start to manage error.

I create an exception handling to treat resources that are not found.

@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    private ResponseEntity<Void> handleResourceNotFoundException(ResourceNotFoundException e) {
        return ResponseEntity.notFound().build();
    }
}

In my Controller I do

@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);
}

I have only a few members, so if I call

localhost:/members/999

I see in the response headers 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

Why I don't get the message: Member not found? Is this a good way to manage errors with spring boot? How to manage different types of errors in the controller?

Автор: bernard deromme Источник Размещён: 19.07.2016 01:31

Ответы (1)


0 плюса

425 Репутация автора

You'll want to change your exception handler to return a body with the error message you want to return, i.e.:

@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");
    }
}
Автор: Dustin Kendall Размещён: 19.07.2016 06:00
Вопросы из категории :
32x32