java Spring问题详细信息和响应实体

kjthegm6  于 2023-02-11  发布在  Java
关注(0)|答案(1)|浏览(188)

在 Spring 6,ProblemDetail可用

@ExceptionHandler(EntityNotFoundException.class)
protected ProblemDetail handleEntityNotFoundException(EntityNotFoundException ex, HttpServletRequest request) {

    ProblemDetail problemDetail = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
    problemDetail.setTitle("entity.not.found");
    return problemDetail;
}

除了直接返回problemDetail之外,是否有任何实用程序可以返回

ResponseEntity<ProblemDetail>
nx7onnlm

nx7onnlm1#

有很多方法!
使用@ResponseBody

@ResponseBody
@ExceptionHandler(EntityNotFoundException.class)
protected ProblemDetail handleEntityNotFoundException(EntityNotFoundException ex, 
                                                      HttpServletRequest request) {
    ProblemDetail problemDetail = forStatusAndDetail(NOT_FOUND, ex.getMessage());
    problemDetail.setTitle("entity.not.found");
    return problemDetail;
}

使用SpringResponseEntitystatic模式:

@ExceptionHandler(EntityNotFoundException.class)
protected ResponseEntity<ProblemDetail> handleEntityNotFoundException(
        EntityNotFoundException ex, 
        HttpServletRequest request) {
    ProblemDetail problemDetail = forStatusAndDetail(NOT_FOUND, ex.getMessage());
    problemDetail.setTitle("entity.not.found");
    return ResponseEntity.ok(problemDetail);
}

支持的其他状态:

accepted()
badRequest()
noContent()
notFound()
unprocessableEntity()

自定义bodyheader的示例:

@GetMapping("/customHeader")
ResponseEntity<String> customHeader() {
    return ResponseEntity.ok()
        .header("Custom-Header", "foo")
        .body("Custom header set");
}

或者使用传统构造函数和自定义状态:

return new ResponseEntity<>(body, HttpStatus.OK);

参考:

相关问题