Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I wanted to handle the exception like 'Request method POST/GET not supported' in response of JSON Format, instead of Error Page.

The reason is any url after abc.com/api/ is my API urls, 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 throws error page saying 'Request Method GET not supported' which is correct. But I want a friendlier error handler in JSON format 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 seem to find solution. Maybe my keywords were not correct. Straight forward here, hope anyone with experience can solve my issue. Thanks in advance.

like image 731
Nick Eng Avatar asked Sep 27 '22 20:09

Nick Eng


1 Answers

You can create a class called DefaultExceptionHandler to trap any exception and return anything you want (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 see more about how to handle exception in Spring MVC, please read following article: Exception Handling in Spring MVC

like image 140
Thanh Nguyen Van Avatar answered Oct 06 '22 01:10

Thanh Nguyen Van