簡體   English   中英

Spring ExceptionHandler不返回有效的響應代碼

[英]Spring ExceptionHandler does not return valid response code

我在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,並且未設置Content-type。 有什么建議么?

你可以這樣嘗試嗎 這是一個代碼段,請根據要求進行修改。

@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);
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM