1

I am not able to create a custom error response in case of an invalid request that returns 405 error HttpStatus.METHOD_NOT_ALLOWED and {message: "invalid endpoint"}

I request the URL with invalid endpoints it is giving me the 404 error with the default message, I want to customise this response.

Correct Url : /api/trains

http://localhost:8080/api/trains

When the user enters other endpoint URLs like

  • /api/trai
  • /api/train
  • api/

For all these invalid endpoint requests (NoHandlerFoundException) I want to throw a customise response with a custom message

I have already added the required code in the application.properties file

spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false
server.error.whitelabel.enabled=false

Controller Code

@RestController
@RequestMapping("/api")
public class TrainController {


@Autowired
private TrainRepository trainrepository;

@GetMapping("/trains")
public ResponseEntity<ArrayList<TrainModel>> getAlltrains(){
    
        ArrayList<TrainModel> trainmodel=(ArrayList<TrainModel>) trainrepository.findAll();
        if (trainmodel.isEmpty()) {
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        }
        return new ResponseEntity<>(trainmodel, HttpStatus.OK);

}

GlobalExceptionHandlingController

@ControllerAdvice
public class GlobalExceptionHandlingController extends ResponseEntityExceptionHandler{


@ExceptionHandler(NoHandlerFoundException.class)
protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex,HttpHeaders headers, HttpStatus status, WebRequest request) {
    HashMap<String,String> responseBody = new HashMap<>();
    responseBody.put("path",request.getContextPath());
    responseBody.put("message","Invalid Endpoint");
    return new ResponseEntity<Object>(responseBody,HttpStatus.METHOD_NOT_ALLOWED);

}

When I try to run the Spring application its giving me error
java.lang.IllegalStateException: Ambiguous @ExceptionHandler method mapped

Deshwal
  • 11
  • 4

0 Answers0