Spring How to handle "POST request method not supported" error for Restful API

I wanted to handle a "POST / GET request method not supported" exception in response to JSON format instead of an error page.

The reason is that any url after abc.com/api/ is my API url, but I don't know how to catch and handle the exception like above.

here's my controller:

@RequestMapping(value="/register", method=RequestMethod.POST)
    @ResponseBody
    public ApiBaseResp register(@RequestBody RegisterReq req , HttpServletResponse res) throws RestException {

}

      

When I call abc.com/api/register with GET, it gives an error page that "Request Method GET not supported" is correct. But I want a more convenient JSON error handler like:

{
"code" : "99",
"message" : "Request MEthod GET not supported"
}

      

Here's my abc-servlet.xml:

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver"
        p:order="1" />

    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" p:order="2">
        <property name="exceptionMappings">
            <props>
                <prop
                    key="com.abc.framework.common.exception.NoPrivilegeException">noPrivilege</prop>
                <prop key="java.lang.Exception">error</prop>
                <prop
                    key="com.abc.framework.common.exception.CustomGenericException">customError</prop>

            </props>
        </property>
    </bean>

      

I've googled but couldn't find a solution. Perhaps my keywords were wrong. Straight ahead, hopefully someone with experience can solve my problem. Thanks in advance.

+3


source to share


2 answers


You can create a class called DefaultExceptionHandler

to catch any exception and return whatever you need (eg: RestError

in this example)

@ControllerAdvice
public class DefaultExceptionHandler {
    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    public ResponseEntity<?> methodNotSupportErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        RestError error = new RestError("BadRequestException", 400, "Method not supported");
        return new ResponseEntity<RestError>(response, HttpStatus.BAD_REQUEST);
    }
}


@JsonPropertyOrder(value = {"error_type", "code", "error_message"})
public class RestError {

    @JsonProperty("code")
    int code;

    @JsonProperty("error_type")
    String type;

    @JsonProperty("error_message")
    String message;

    public RestError() {
        super();
    }

    public RestError(String type, int code, String message) {
        this.code = code;
        this.type = type;
        this.message = message;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

      



To learn more about how to handle exceptions in Spring MVC read the following article: Handling Exceptions in Spring MVC

+3


source


I would suggest solving this in any of the following ways.



  • Create interceptor

    and submit a request using this method, override preHandle

    and postHandle

    , and from there postHandle

    you can prepare a response of your choice.

  • Or you can create Filter

    and there you can check the HTTP status code and then change the message response

    .

0


source







All Articles