简体   繁体   中英

Error response in json format for Spring interceptor

I am writing a REST based web service. I need to return all the responses as JSON format. I have an interceptor to validate my authentication parameters. On authentication failure scenario, I have to return the error response in JSON format.

Currently i am doing

response.setHeader("Content-Type","application/json"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "{\\"error\\":\\"Missing Authentication Parameters\\"}");

The response body is coming as below.

JBoss Web/2.1.3.GA - Error report

HTTP Status 401 - {"error":"Missing Authentication Parameters"}

Status report 状态报告

{"error":"Missing Authentication Parameters"} {“错误”:“缺少身份验证参数”}

This request requires HTTP authentication ({"error":"Missing Authentication Parameters"}). 此请求需要HTTP身份验证({“错误”:“缺少身份验证参数”})。

JBoss Web/2.1.3.GA

I need just the JSON string in response. Please help me.

You should probably be using spring-security for this. If you want to do it by hand, an alternative to using sendError on the response is to use spring MVC's @ExceptionHandler along with content negotiation to return JSON.

First define an error class*:

public class Error {
    public message;
    public exception;
    public Error(String message, Exception ex) {
        this.message = message;
        this.exception = ex;
    }
}

And an exception:

public class NotAuthenticatedException extends Exception {
    // ...
}

Then in your controller you throw an exception at the appropriate time, catch it with @ExceptionHandler and return a ResponseEntity containing an Error instance and the appropriate error code.

@Controller
public class SimpleController {
    @RequestMapping(...)
    public String aMethod() {
        // ...
        throw new NotAuthenticatedException("Missing Authentication Parameters");
    }

    @ExceptionHandler(NotAuthenticatedException.class)
    public ResponseEntity<Error> handleNotAuthenticatedException(
            NotAuthenticatedException ex, 
            HttpServletRequest request) {
        return new ResponseEntity<Error>(
            new Error(ex.getMessage(), ex), 
            HttpStatus.UNAUTHORIZED
        );
    }
}

*use getters/setters to please the java convention gods

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM