2017-05-31 55 views
0
使用Spring REST定义自定义错误消息

我托管在WebLogic 10.3.6的REST API 春天启动的应用程序,我想实现这些功能2:在Weblogic上

  1. 每当我的自定义异常发生时我想要发送带有消息的http响应,例如500 - “请求不能因为某件事解析......”
  2. 每当任何引发错误我想获得那通常打印到控制台(用于调试)堆栈跟踪

我试图解决第一部分按以下方式:

@ControllerAdvice 
public class ExceptionHandlerAdvice { 


    @ExceptionHandler(MyException.class) 
    public ResponseEntity handleException(MyException e) { 

     return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage()); 
    } 

但是作为回应,我只拿到500内部服务器错误,没有消息

至于第二部分我想simmilar的做法,但没有错误消息无论是。

我该如何解决这个问题?

编辑:

@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason="This is a message I'd like to send") 

它的工作原理,但我必须从代​​码中添加一些变量的消息,并且此: 我能达到被删除ExceptionHandlerAdvice和我的异常类使用注释,而不是像这样最好方法不允许它

EDIT2: 这是一个有点怪异,也许WebLogic Server中的行为,但是当我设置则httpStatus到HttpStatus.ACCEPTED我可以看到该消息,如果是HttpStatus.Forbidden或其他任何4xx错误我刚收到错误消息

+0

你好虫族,人族在这里。也许你的服务抛出ExceptionHandlerAdvice无法控制的异常,尝试调试并打印到控制台与system.out – ducanhng

+0

我特意在一个方法抛出MyException:抛出新的MyException(“some message”); – Zerg

+0

你好zerg,在handleException方法中尝试抛出异常。在这里引用:即使我使用@ResponseStatus注释,并添加原因参数如: @ResponseStatus(https://stackoverflow.com/questions/39517876/spring-boot-not-overriding-exception-using-controlleradvice?rq=1 – ducanhng

回答

1

用消息和状态创建'ResponseEntity'对象并返回它,它将显示错误消息。

/** 
* HTTP_STATUS - 500 -Service Unavailable. 
* 
* @param exception 
*   Catches the following: MyException 
* @return 
*/ 
@ExceptionHandler({ MyException.class}) 
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) 
@ResponseBody 
public static ResponseEntity<?> handleConnectionErrorResponse(MyException exception) { 
    return new ResponseEntity<String>("Some error occurred at server", HttpStatus.INTERNAL_SERVER_ERROR); 
} 
+0

这仍然不会给我超过500内部服务器错误没有错误信息 – Zerg

+0

当我使用HttpStatus.ACCEPTED时,我无法获得消息,当我看到消息,任何想法? – Zerg

+0

没有遇到过这个问题,不知道是什么原因造成的。 – Sudhakar

0

不要返回的东西,抛出:

@ResponseStatus(value = HttpStatus.UNPROCESSABLE_ENTITY) 
public class UnprocessableEntity extends RuntimeException { 

    public UnprocessableEntity(String string) { 
     super(string); 
    } 

} 

或类似的另一件事。

+0

)@ResponseStatus (值= HttpStatus。INTERNAL_SERVER_ERROR,reason =“我想打印的信息”) 我无法将参数从代码传递到错误信息,所以这不是答案 – Zerg

+0

'String msg =“您的代码中的信息”;抛出新的UnprocessableEntity(msg);' 顺便说一句'UnprocessableEntity'是一个n自定义的'Exception',这意味着只要你扩展了'RuntimeException'就可以建立自己的。 – Zorglube

+0

是的,这是我在做什么,它不会返回消息,只有状态代码像500,422等 – Zerg

0

我也经历了同样的要求。 以下是为我工作的代码:

String errMsg = "{\"errorMessage\":\"Parking Slot is not available\"}"; 
return new ResponseEntity<String>(errMsg, HttpStatus.INTERNAL_SERVER_ERROR); 

errMsg应该在你想要的格式写入。就像我在JSON中需要响应一样。

希望这会帮助你们中的一些人