如何在找不到资源时在@ExceptionHandler中返回JSON

时间:2016-07-27 07:30:28

标签: json exception-handling spring-web

如果发生错误,提供资源(.js; .css ...)的应用程序如何返回 JSON 实体?

我根据this blog写了ControllerExceptionHandler

package com.my.rest;

import com.my.rest.errors.ErrorMessage;
import com.my.rest.errors.ErrorMessageFactory;
import com.my.service.errors.NotFoundException;
import com.my.service.errors.ValidationException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import static org.springframework.http.HttpStatus.NOT_FOUND;

@ControllerAdvice
@ResponseBody
public class GlobalControllerExceptionHandler extends ResponseEntityExceptionHandler {

    @Autowired
    private ErrorMessageFactory messageFactory;

    @ResponseStatus(NOT_FOUND)
    @ExceptionHandler({NotFoundException.class})
    public ResponseEntity<Object> handleServiceException(RuntimeException e, WebRequest request) {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);

        return handleExceptionInternal(e, messageFactory.generateMessage(e), headers, HttpStatus.NOT_FOUND, request);
    }

}

如果请求网址为:https://my-server/resources/a.js,但未找到a.js,则此 ExceptionHandler 会导致HttpMediaTypeNotAcceptableException引发AbstractMessageConverterMethodProcessor,因为ContentNegotiationManager使用基于扩展程序.js的策略,并确定ErrorMessage不适用于媒体类型application/javascript

我的问题是:是否有办法忽略媒体类型检查以始终发送JSON错误响应,以便客户端错误管理可以解析它?

谢谢

0 个答案:

没有答案