相关疑难解决方法(0)

如何在返回String的Spring MVC @ResponseBody方法中响应HTTP 400错误?

我使用Spring MVC作为一个简单的JSON API,@ResponseBody基于以下方法.(我已经有一个直接生成JSON的服务层.)

@RequestMapping(value = "/matches/{matchId}", produces = "application/json")
@ResponseBody
public String match(@PathVariable String matchId) {
    String json = matchService.getMatchJson(matchId);
    if (json == null) {
        // TODO: how to respond with e.g. 400 "bad request"?
    }
    return json;
}
Run Code Online (Sandbox Code Playgroud)

问题是,在给定的场景中,用HTTP 400错误响应的最简单,最干净的方法是什么?

我确实遇到过这样的方法:

return new ResponseEntity(HttpStatus.BAD_REQUEST);
Run Code Online (Sandbox Code Playgroud)

...但我不能在这里使用它,因为我的方法的返回类型是String,而不是ResponseEntity.

java spring spring-mvc http-error

366
推荐指数
8
解决办法
34万
查看次数

使用@ExceptionHandler 根据请求动态返回 HTTP 状态代码

我想根据响应对象错误动态返回 HTTPStatus 代码,如 400、400、404 等。我被提到了这个问题 -使用 spring 3 restful编程方式更改 http 响应状态,但它没有帮助。

我有一个带有@ExceptionHandler方法的控制器类

@ExceptionHandler(CustomException.class)
    @ResponseBody
    public ResponseEntity<?> handleException(CustomException e) {
        return new ResponseEntity<MyErrorResponse>(
                new MyErrorResponse(e.getCode(), ExceptionUtility.getMessage(e.getMessage())), 
                ExceptionUtility.getHttpCode(e.getCode()));
    }
Run Code Online (Sandbox Code Playgroud)

ExceptionUtility是一个类,我在其中使用了上面使用的两种方法(getMessagegetCode)。

public class ExceptionUtility {
    public static String getMessage(String message) {
        return message;
    }

    public static HttpStatus getHttpCode(String code) {
        return HttpStatus.NOT_FOUND; //how to return status code dynamically here ?
    }
}
Run Code Online (Sandbox Code Playgroud)

我不想检查 if 条件并相应地返回响应代码,有没有其他更好的方法来做到这一点?

java spring http-status-codes exceptionhandler

5
推荐指数
2
解决办法
4322
查看次数