简体   繁体   English

使用Spring REST的URL中的错误消息

[英]Error message in URL using Spring REST

I am developing a project using Spring REST web services, where I need to show graceful error messages when an exception/error occurs. 我正在使用Spring REST Web服务开发一个项目,当发生异常/错误时,我需要在其中显示优美的错误消息。 I followed this tutorial ( http://www.javacodegeeks.com/2013/02/exception-handling-for-rest-with-spring-3-2.html ) for exception handling using SpringREST. 我按照本教程( http://www.javacodegeeks.com/2013/02/exception-handling-for-rest-with-spring-3-2.html )进行了使用SpringREST的异常处理。 I get the proper output when there is no exception/error ie in form of an XML. 没有异常/错误(即XML形式)时,我会得到正确的输出。 The issue arises when an exception occurs. 发生异常时会出现此问题。 Here is part of the code base where an exception occurs if I do not pass the testId in 这是代码库的一部分,如果我不通过testId,则会发生异常

localhost:8080/test?testId=

The class outputs a response in form of a XML, so when an exception occurs, instead of showing the error message as figure 1 below, it shows error message as figure 2. If I do "View Page Source", I get the correct exception message (as figure 1). 该类以XML的形式输出响应,因此,当发生异常时,与其显示错误消息(如图1所示),不如显示图2所示。如果执行“查看页面源代码”,则可以得到正确的异常消息(如图1所示)。 But I need the exception message directly. 但是我直接需要异常消息。 Could anyone, please suggest a solution? 有人可以提出解决方案吗?

 @RequestMapping(value = "/test",
       method = RequestMethod.GET,
       produces = "application/xml")
 public @ResponseBody String testResource(
        @RequestParam(value="testId", required=true) String testId)
                throws CustomRestException{

    if (testId == null || testId.equals(""))
    {
        LOG.error( "testResource(): " + TestUtilsException.NULL_TEST_ID_ERROR_MSG );
                    //The error message is: The test Id is required and cannot be null or empty
        throw new CustomRestException(TestUtilsException.NULL_TEST_ID_ERROR_MSG);
    }
}

Figure 1 图1 在此处输入图片说明 Figure 2 图2 在此处输入图片说明

Other helper classes: 其他辅助类:

@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    public RestResponseEntityExceptionHandler() {
       super();
    }

    @ExceptionHandler(value = { CustomRestException.class })
    @ResponseBody
    protected ResponseEntity<Object> handleNotFound(final RuntimeException ex, final WebRequest  request) {
         final String bodyOfResponse = ex.getMessage();
         return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(),   HttpStatus.INTERNAL_SERVER_ERROR, request);
     }
}

 public class CustomRestException extends RuntimeException {

    public CustomRestException() {
        super();
    }
    public CustomRestException(final String message, final Throwable cause) {
        super(message, cause);
    }
    public CustomRestException(final String message) {
        super(message);
    }
    public CustomRestException(final Throwable cause) {
        super(cause);
    }
}

@ControllerAdvice方法应该可以工作,尽管我认为不需要基类-您可以在Spring 4中使用@ExceptionHandler 。但是您将返回无法转换为Xml的响应主体(这是一个纯字符串) ,因此您得到的响应为空,可能是405,而不是500。如果要Xml响应,则必须提供一个可以转换的主体(或者提供可以执行此操作的HttpMessageConverter )。

Consider doing this. 考虑这样做。

public class BaseController{ 公共类BaseController {

    @ExceptionHandler(value = { CustomRestException.class })
    protected @ResponseBody ResponseEntity<ErrorResponse > handleNotFound(final RuntimeException ex, final WebRequest  request) {
        System.out.println("is executed in handler");
         final String bodyOfResponse = ex.getMessage();
         return new ResponseEntity<ErrorResponse >(new ErrorResponse (bodyOfResponse), null, HttpStatus.NOT_FOUND);
     }
}

In your controller do this. 在您的控制器中执行此操作。

@Controller
public class HomeController extends BaseController {//Your code here} 

And create this class. 并创建此类。

@XmlRootElement
public class ErrorResponse {

    public String error;
}

Finally add to your class the following code 最后将以下代码添加到您的类中

if (testId == null || testId.equals(""))
                {
                    throw new CustomRestException("DD");
                }

That will create an XML response as follows. 这将创建一个XML响应,如下所示。

This XML file does not appear to have any style information associated with it. 此XML文件似乎没有与之关联的任何样式信息。 The document tree is shown below. 文档树如下所示。

<successResponse> <error>DD</error> </successResponse>

This will handle all the exception an is not needed to add @ControllerAdvice, that seems need to add their own MessageConverters that is why the answer is not converted to XML, I read that here . 这将处理所有不需要添加@ControllerAdvice的异常,这似乎需要添加自己的MessageConverters,这就是为什么答案未转换为XML的原因,我在这里读到

I added ,produces = "application/xml" and remove it, and is still working as I think you want. 我添加了,produces = "application/xml"并将其删除,并且仍然可以按照我认为的方式工作。 Please let me know if this was useful. 请让我知道这是否有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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