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

时间:2013-04-26 09:16:16

标签: java spring spring-mvc http-error

我正在使用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;
}

问题是,在给定的情况下,用最简单,最干净的方式回应HTTP 400错误

我确实遇到过像:

这样的方法
return new ResponseEntity(HttpStatus.BAD_REQUEST);

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

13 个答案:

答案 0 :(得分:551)

将您的退货类型更改为ResponseEntity<>,然后您可以在下面使用400

return new ResponseEntity<>(HttpStatus.BAD_REQUEST);

并提供正确的请求

return new ResponseEntity<>(json,HttpStatus.OK);

更新1

在Spring 4.1之后,ResponseEntity中的辅助方法可以用作

return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);

return ResponseEntity.ok(json);

答案 1 :(得分:94)

这样的事情应该有用,我不确定是否有更简单的方法:

@RequestMapping(value = "/matches/{matchId}", produces = "application/json")
@ResponseBody
public String match(@PathVariable String matchId, @RequestBody String body,
            HttpServletRequest request, HttpServletResponse response) {
    String json = matchService.getMatchJson(matchId);
    if (json == null) {
        response.setStatus( HttpServletResponse.SC_BAD_REQUEST  );
    }
    return json;
}

答案 2 :(得分:50)

不一定是最紧凑的方式,但IMO非常干净

if(json == null) {
    throw new BadThingException();
}
...

@ExceptionHandler(BadThingException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public @ResponseBody MyError handleException(BadThingException e) {
    return new MyError("That doesnt work");
}

如果使用Spring 3.1+,编辑你可以在异常处理程序方法中使用@ResponseBody,否则使用ModelAndView或其他东西。

https://jira.springsource.org/browse/SPR-6902

答案 3 :(得分:45)

我会稍微改变一下实现:

首先,我创建了一个UnknownMatchException

@ResponseStatus(HttpStatus.NOT_FOUND)
public class UnknownMatchException extends RuntimeException {
    public UnknownMatchException(String matchId) {
        super("Unknown match: " + matchId);
    }
}

请注意使用@ResponseStatus,这将被Spring的ResponseStatusExceptionResolver识别。如果抛出异常,它将创建具有相应响应状态的响应。 (我也冒昧地将状态代码更改为404 - Not Found,我认为这更适合此用例,但如果您愿意,可以坚持HttpStatus.BAD_REQUEST。)


接下来,我会将MatchService更改为具有以下签名:

interface MatchService {
    public Match findMatch(String matchId);
}

最后,我会更新控制器并委托Spring的MappingJackson2HttpMessageConverter自动处理JSON序列化(默认情况下,如果你将Jackson添加到类路径并添加@EnableWebMvc或{{1您的配置,请参阅reference docs):

<mvc:annotation-driven />

注意,将域对象与视图对象或DTO对象分开是很常见的。这可以通过添加一个返回可序列化JSON对象的小型DTO工厂来轻松实现:

@RequestMapping(value = "/matches/{matchId}", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Match match(@PathVariable String matchId) {
    // throws an UnknownMatchException if the matchId is not known 
    return matchService.findMatch(matchId);
}

答案 4 :(得分:31)

这是一种不同的方法。创建一个使用select * from pcarscall1 WHERE CALLKEY > ? OR ModDate >= ? 注释的自定义Exception,如下所示。

@ResponseStatus

在需要时抛出它。

@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "Not Found")
public class NotFoundException extends Exception {

    public NotFoundException() {
    }
}

在此处查看Spring文档:http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-ann-annotated-exceptions

答案 5 :(得分:15)

如某些答案所述,可以为要返回的每个HTTP状态创建一个异常类。我不喜欢为每个项目创建每个状态的类的想法。以下是我提出的内容。

  • 创建接受HTTP状态的通用异常
  • 创建Controller Advice异常处理程序

让我们来看看代码

package com.javaninja.cam.exception;

import org.springframework.http.HttpStatus;


/**
 * The exception used to return a status and a message to the calling system.
 * @author norrisshelton
 */
@SuppressWarnings("ClassWithoutNoArgConstructor")
public class ResourceException extends RuntimeException {

    private HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;

    /**
     * Gets the HTTP status code to be returned to the calling system.
     * @return http status code.  Defaults to HttpStatus.INTERNAL_SERVER_ERROR (500).
     * @see HttpStatus
     */
    public HttpStatus getHttpStatus() {
        return httpStatus;
    }

    /**
     * Constructs a new runtime exception with the specified HttpStatus code and detail message.
     * The cause is not initialized, and may subsequently be initialized by a call to {@link #initCause}.
     * @param httpStatus the http status.  The detail message is saved for later retrieval by the {@link
     *                   #getHttpStatus()} method.
     * @param message    the detail message. The detail message is saved for later retrieval by the {@link
     *                   #getMessage()} method.
     * @see HttpStatus
     */
    public ResourceException(HttpStatus httpStatus, String message) {
        super(message);
        this.httpStatus = httpStatus;
    }
}

然后我创建一个控制器建议类

package com.javaninja.cam.spring;


import com.javaninja.cam.exception.ResourceException;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;


/**
 * Exception handler advice class for all SpringMVC controllers.
 * @author norrisshelton
 * @see org.springframework.web.bind.annotation.ControllerAdvice
 */
@org.springframework.web.bind.annotation.ControllerAdvice
public class ControllerAdvice {

    /**
     * Handles ResourceExceptions for the SpringMVC controllers.
     * @param e SpringMVC controller exception.
     * @return http response entity
     * @see ExceptionHandler
     */
    @ExceptionHandler(ResourceException.class)
    public ResponseEntity handleException(ResourceException e) {
        return ResponseEntity.status(e.getHttpStatus()).body(e.getMessage());
    }
}

使用它

throw new ResourceException(HttpStatus.BAD_REQUEST, "My message");

http://javaninja.net/2016/06/throwing-exceptions-messages-spring-mvc-controller/

答案 6 :(得分:14)

最简单的方法是抛出ResponseStatusException

    @RequestMapping(value = "/matches/{matchId}", produces = "application/json")
    @ResponseBody
    public String match(@PathVariable String matchId, @RequestBody String body) {
        String json = matchService.getMatchJson(matchId);
        if (json == null) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND);
        }
        return json;
    }

答案 7 :(得分:10)

我在春季启动应用程序中使用它

@RequestMapping(value = "/matches/{matchId}", produces = "application/json")
@ResponseBody
public ResponseEntity<?> match(@PathVariable String matchId, @RequestBody String body,
            HttpServletRequest request, HttpServletResponse response) {

    Product p;
    try {
      p = service.getProduct(request.getProductId());
    } catch(Exception ex) {
       return new ResponseEntity<String>(HttpStatus.BAD_REQUEST);
    }

    return new ResponseEntity(p, HttpStatus.OK);
}

答案 8 :(得分:2)

另一种方法是将@ExceptionHandler@ControllerAdvice结合使用,以将所有处理程序集中在同一个类中,否则,必须将处理程序方法放在要管理异常的每个控制器中。

您的处理程序类:

@ControllerAdvice
public class MyExceptionHandler extends ResponseEntityExceptionHandler {

  @ExceptionHandler(MyBadRequestException.class)
  public ResponseEntity<MyError> handleException(MyBadRequestException e) {
    return ResponseEntity
        .badRequest()
        .body(new MyError(HttpStatus.BAD_REQUEST, e.getDescription()));
  }
}

您的自定义例外:

public class MyBadRequestException extends RuntimeException {

  private String description;

  public MyBadRequestException(String description) {
    this.description = description;
  }

  public String getDescription() {
    return this.description;
  }
}

现在,您可以从任何控制器抛出异常,并且可以在通知类内部定义其他处理程序。

答案 9 :(得分:0)

使用Spring Boot,我不完全确定为什么这是必要的(即使在/error上定义了@ResponseBody,我得到了@ExceptionHandler后备,但是以下内容本身不起作用:

@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(IllegalArgumentException.class)
public ErrorMessage handleIllegalArguments(HttpServletRequest httpServletRequest, IllegalArgumentException e) {
    log.error("Illegal arguments received.", e);
    ErrorMessage errorMessage = new ErrorMessage();
    errorMessage.code = 400;
    errorMessage.message = e.getMessage();
    return errorMessage;
}

它仍然引发了异常,显然是因为没有可生成的媒体类型被定义为请求属性:

// AbstractMessageConverterMethodProcessor
@SuppressWarnings("unchecked")
protected <T> void writeWithMessageConverters(T value, MethodParameter returnType,
        ServletServerHttpRequest inputMessage, ServletServerHttpResponse outputMessage)
        throws IOException, HttpMediaTypeNotAcceptableException, HttpMessageNotWritableException {

    Class<?> valueType = getReturnValueType(value, returnType);
    Type declaredType = getGenericType(returnType);
    HttpServletRequest request = inputMessage.getServletRequest();
    List<MediaType> requestedMediaTypes = getAcceptableMediaTypes(request);
    List<MediaType> producibleMediaTypes = getProducibleMediaTypes(request, valueType, declaredType);
if (value != null && producibleMediaTypes.isEmpty()) {
        throw new IllegalArgumentException("No converter found for return value of type: " + valueType);   // <-- throws
    }

// ....

@SuppressWarnings("unchecked")
protected List<MediaType> getProducibleMediaTypes(HttpServletRequest request, Class<?> valueClass, Type declaredType) {
    Set<MediaType> mediaTypes = (Set<MediaType>) request.getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
    if (!CollectionUtils.isEmpty(mediaTypes)) {
        return new ArrayList<MediaType>(mediaTypes);

所以我添加了它们。

@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(IllegalArgumentException.class)
public ErrorMessage handleIllegalArguments(HttpServletRequest httpServletRequest, IllegalArgumentException e) {
    Set<MediaType> mediaTypes = new HashSet<>();
    mediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
    httpServletRequest.setAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, mediaTypes);
    log.error("Illegal arguments received.", e);
    ErrorMessage errorMessage = new ErrorMessage();
    errorMessage.code = 400;
    errorMessage.message = e.getMessage();
    return errorMessage;
}

这让我获得了支持兼容的媒体类型&#34;但是它仍然没有用,因为我的ErrorMessage有问题:

public class ErrorMessage {
    int code;

    String message;
}

JacksonMapper没有把它作为&#34;可转换&#34;,所以我不得不添加getter / setter,我还添加了@JsonProperty注释

public class ErrorMessage {
    @JsonProperty("code")
    private int code;

    @JsonProperty("message")
    private String message;

    public int getCode() {
        return code;
    }

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

    public String getMessage() {
        return message;
    }

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

然后我按预期收到了我的留言

{"code":400,"message":"An \"url\" parameter must be defined."}

答案 10 :(得分:0)

您也可以throw new HttpMessageNotReadableException("error description")受益于Spring的default error handling

但是,就像那些默认错误一样,不会设置任何响应正文。

当拒绝可能只是手工制作的请求时,我发现这些功能很有用,因为这可能掩盖了基于更深入的自定义验证及其标准而拒绝了该请求的事实。

Hth, dtk

答案 11 :(得分:0)

带有状态代码的自定义响应

就这样:

class Response<T>(
        val timestamp: String = DateTimeFormatter
                .ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS")
                .withZone(ZoneOffset.UTC)
                .format(Instant.now()),
        val code: Int = ResultCode.SUCCESS.code,
        val message: String? = ResultCode.SUCCESS.message,
        val status: HttpStatus = HttpStatus.OK,
        val error: String? = "",
        val token: String? = null,
        val data: T? = null
) : : ResponseEntity<Response.CustomResponseBody>(status) {

data class CustomResponseBody(
        val timestamp: String = DateTimeFormatter
                .ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS")
                .withZone(ZoneOffset.UTC)
                .format(Instant.now()),
        val code: Int = ResultCode.SUCCESS.code,
        val message: String? = ResultCode.SUCCESS.message,
        val error: String? = "",
        val token: String? = null,
        val data: Any? = null
)

override fun getBody(): CustomResponseBody? = CustomResponseBody(timestamp, code, message, error, token, data)

答案 12 :(得分:-2)

我认为这个帖子实际上有最简单,最干净的解决方案,不会牺牲Spring提供的JSON军事工具:

https://stackoverflow.com/a/16986372/1278921