0

I am using Spring Boot 3 to develop a simple Rest API and want to handle exceptions using @RestControllerAdvice, but my code is throwing a 500 error even if the code in @exceptionHandler is throwing a 404 error code. I verified in debugging that execution reaches the ExceptionHandler method, but the default exception is still thrown. 

Below is sample code for:

@RestControllerAdvice
public class ControllerExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    @ResponseStatus(code = HttpStatus.NOT_FOUND)
    public Messsage resourceNotFoundException(ResourceNotFoundException exception, WebRequest request) {
        return new Messsage(HttpStatus.NOT_FOUND.value(), exception.getMessage(), LocalDateTime.now());
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(code = HttpStatus.NOT_FOUND)
    public Messsage globalException(Exception exception, WebRequest request) {
        return new Messsage(HttpStatus.NOT_FOUND.value(), exception.getMessage(), LocalDateTime.now());
    }
}
Raushan Kumar
  • 1,195
  • 12
  • 21

1 Answers1

1

Try to remove ResponseEntityExceptionHandler . which some ExceptionHandler has defined and it may catch exception before you custom exceptionHandler. I had made some unit test here is code sample;

  • Application
@SpringBootApplication
public class AccountApplication {
    public static void main(String[] args) {
        SpringApplication.run(AccountApplication.class);
    }
}

  • Controller

/**
 * @author pengpeng
 * @description
 * @date 2023/2/13
 */
@RequestMapping
@RestController
public class AccountController {

    @GetMapping("/test/{args}")
    public String testError(@PathVariable ("args") String args) throws IllegalAccessException {
        if (args .equals("ill")){
            throw new IllegalAccessException();

        } else if (args.equals("exception")) {
            throw new RuntimeException();
        }else {
            return "success";
        }
    }

}

  • exceptionHandler

/**
 * @author pengpeng
 * @description
 * @date 2023/2/13
 */
@RestControllerAdvice
public class ControllerException extends ResponseEntityResultHandler {


    public ControllerException(List<HttpMessageWriter<?>> writers, RequestedContentTypeResolver resolver) {
        super(writers, resolver);
    }

    public ControllerException(List<HttpMessageWriter<?>> writers, RequestedContentTypeResolver resolver, ReactiveAdapterRegistry registry) {
        super(writers, resolver, registry);
    }

    @ExceptionHandler
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public String illegalFail(IllegalAccessException exception){
        return "illegalFail";
    }



    @ExceptionHandler
    @ResponseStatus(HttpStatus.BAD_GATEWAY)
    public String fail(Exception exception){
        return "fail";
    }
}

after application start use the default application port to initiates HTTP call

  • http
127.0.0.1/test/ill
127.0.0.1/test/exception
127.0.0.1/test/success
Peng
  • 653
  • 8
  • Hi Peng, Thank you for your response! I have tried with and without extending ResponseEnttiyResultHandler but it does not work any way. Please see below my Controller code for reference: – Ranjit Singh Feb 13 '23 at 23:58
  • @ RestController @ RequestMapping("/api") public class VesselController { @Autowired private VesselService vesselService; @PostMapping("/vessels") public ResponseEntity addVessel(@RequestBody Vessel vessel) throws ResourceNotFoundException { try { vesselService.createVessel(vessel); } catch (Exception e) { throw new ResourceNotFoundException(e.getMessage()); } return new ResponseEntity<>(vessel, HttpStatus.OK); } } – Ranjit Singh Feb 14 '23 at 00:00
  • not sure the code ``` vesselService.createVessel(vessel); ``` will thrown the exception which will be captured by try ... catch try to thrown ```ResourceNotFoundException``` directly if the example not work in correct way ,you shoud check your SpringApplication @RestController @RequestMapping("/api") public class VesselController { @PostMapping("/vessels") public ResponseEntity addVessel(@RequestBody Vessel vessel) throws ResourceNotFoundException { throw new ResourceNotFoundException(e.getMessage()); } } ``` – Peng Feb 14 '23 at 01:47