Spring Boot 返回自定义 HTTP 状态码

2020-04-16  本文已影响0人  又语

本文介绍 Spring Boot 返回自定义 HTTP 状态码的方法。


目录


使用 ResponseEntity 返回值

@GetMapping("/ResponseEntity")
public ResponseEntity<String> byResponseEntity() {
    return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}

抛出 @ResponseStatus 注解的异常类

@GetMapping("/Exception")
public String byException() {
    throw new ForbiddenException();
}

@ResponseStatus(value = HttpStatus.FORBIDDEN, reason = "Forbidden")
public static class ForbiddenException extends RuntimeException {
}

使用 @ControllerAdvice@ExceptionHandler 注解

上一篇 下一篇

猜你喜欢

热点阅读