gpt4 book ai didi

java - Spring ExceptionHandler 未返回有效的响应代码

转载 作者:行者123 更新时间:2023-12-02 09:48:37 25 4
gpt4 key购买 nike

我在 spring RestController 中有这样的异常处理程序。

   @ExceptionHandler(AuthException.class)
public ResponseEntity<String> handleCustomException(AuthException ex, Writer writer) throws IOException {

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

ResponseEntity responseEntity = new ResponseEntity(headers, HttpStatus.FORBIDDEN);
(new ObjectMapper()).writeValue(writer, ex.getAsMap());

return responseEntity;
}

我期望结果:内容类型:application-json状态:403和正文:

{"date":"06-06-2019 18:36:34","errorCode":"102","error":"Login or password is not right","message":"Access denied"}

但是结果是:状态:200,未设置内容类型。有什么建议吗?

最佳答案

你可以这样尝试吗?这是一个代码片段,请根据要求进行修改。

@ControllerAdvice
public class GlobalExceptionHandler{
@ExceptionHandler(MyCustomException.class)
@ResponseBody
public ResponseEntity<?> handleCustomException(MyCustomException e) {
String bodyJson = "Fatal Exception while performing.";
return ResponseEntity.status(HttpStatus.FORBIDDEN).contentType(MediaType.APPLICATION_JSON).body(bodyJson);
}
}

关于java - Spring ExceptionHandler 未返回有效的响应代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56480997/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com