我正在使用这样的方法
def register_user(request):
if request.method == 'POST':
form = UserForm(request.POST) # create form object
if form.is_valid():
email = form.cleaned_data['email']
user = User(email=email)
user.save()
return HttpResponseRedirect('/accounts/register_success')
我想在发生异常时返回一些文本消息,但现在我只返回status和null对象。有可能吗?
答案 0 :(得分:74)
正如 Sotirios Delimanolis已经在评论中指出的那样,有两种选择:
ResponseEntity
并显示错误消息像这样改变你的方法:
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity getUser(@RequestHeader(value="Access-key") String accessKey,
@RequestHeader(value="Secret-key") String secretKey) {
try {
// see note 1
return ResponseEntity
.status(HttpStatus.CREATED)
.body(this.userService.chkCredentials(accessKey, secretKey, timestamp));
}
catch(ChekingCredentialsFailedException e) {
e.printStackTrace(); // see note 2
return ResponseEntity
.status(HttpStatus.FORBIDDEN)
.body("Error Message");
}
}
注1 :您不必使用ResponseEntity
构建器,但我发现它有助于保持代码的可读性。它还有助于记住特定HTTP状态代码的响应应包含哪些数据。例如,状态代码为201的响应应包含指向Location
标头中新创建的资源的链接(请参阅Status Code Definitions)。这就是Spring提供方便的构建方法ResponseEntity.created(URI)
的原因。
注意2 :请勿使用printStackTrace()
,而是使用记录器。
@ExceptionHandler
从方法中删除try-catch块并让它抛出异常。然后在使用@ControllerAdvice
注释的类中创建另一个方法,如下所示:
@ControllerAdvice
public class ExceptionHandlerAdvice {
@ExceptionHandler(ChekingCredentialsFailedException.class)
public ResponseEntity handleException(ChekingCredentialsFailedException e) {
// log exception
return ResponseEntity
.status(HttpStatus.FORBIDDEN)
.body("Error Message");
}
}
请注意,允许使用@ExceptionHandler
注释的方法具有非常灵活的签名。有关详细信息,请参阅Javadoc。
答案 1 :(得分:9)
这是另一种选择。创建一个带有状态代码和消息的通用异常。然后创建一个异常处理程序使用异常处理程序从异常中检索信息并返回给服务的调用者。
http://javaninja.net/2016/06/throwing-exceptions-messages-spring-mvc-controller/
public class ResourceException extends RuntimeException {
private HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
public HttpStatus getHttpStatus() {
return httpStatus;
}
/**
* Constructs a new runtime exception with the specified detail message.
* The cause is not initialized, and may subsequently be initialized by a
* call to {@link #initCause}.
* @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()}
* method.
*/
public ResourceException(HttpStatus httpStatus, String message) {
super(message);
this.httpStatus = httpStatus;
}
}
然后使用异常处理程序检索信息并将其返回给服务调用者。
@ControllerAdvice
public class ExceptionHandlerAdvice {
@ExceptionHandler(ResourceException.class)
public ResponseEntity handleException(ResourceException e) {
// log exception
return ResponseEntity.status(e.getHttpStatus()).body(e.getMessage());
}
}
然后在需要时创建例外。
throw new ResourceException(HttpStatus.NOT_FOUND, "We were unable to find the specified resource.");
答案 2 :(得分:0)
return new ResponseEntity<>(GenericResponseBean.newGenericError("Error during the calling the service", -1L), HttpStatus.EXPECTATION_FAILED);
答案 3 :(得分:0)
正在评估另一个服务引起的错误响应...
这是我评估错误的解决方案:
try {
return authenticationFeign.signIn(userDto, dataRequest);
}catch(FeignException ex){
//ex.status();
if(ex.status() == HttpStatus.UNAUTHORIZED.value()){
System.out.println("is a error 401");
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
return new ResponseEntity<>(HttpStatus.OK);
}