how to remove "Request method 'GET' not supported' error from the screen in java

55 views Asked by At

When i access the URL api in the browser, i get this error in the screen:

Request method 'GET' not supported

What i want is to completely remove this error when i access the url directly in the browser. i tried creating a exception handler logic to catch the error and display a blank text but it does not work

here is my code:

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.HttpRequestMethodNotSupportedException;

@controllerAdvice
public class GlobalExceptionHandler{
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResponseEntity<String> handleMethodNotAllowedExceptionException(HttpRequestMethodNotSupportedException ex){
   
      return new ResponseEntity<>("",HttpStatus.METHOD_NOT_ALLOWED);

   }
}

Is there a way to remove this error from the screen? any help would be appreciated.

1

There are 1 answers

0
SerhiiH On

In Spring Boot 3.2, this code works perfectly:

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.HttpRequestMethodNotSupportedException;

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResponseEntity<String> exceptionHandler(HttpRequestMethodNotSupportedException ex) {
        return new ResponseEntity<>("", HttpStatus.METHOD_NOT_ALLOWED);
    }
}

If your project doesn't pick GlobalExceptionHandler, it means that there are discovery problems or you have another ExceptionHandler bean somehow overrides that handler.
Make sure you updated project to the latest versions and GlobalExceptionHandler class in package that is discoverable for spring.

For example if app defined like that:

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

Make sure you put GlobalExceptionHandler class into com.example.demo package or it's sub packages.