本文介绍 Spring Boot 返回自定义 HTTP 状态码的方法。
目录
- 使用
ResponseEntity
返回值 - 抛出
@ResponseStatus
注解的异常类 - 使用
@ControllerAdvice
和@ExceptionHandler
注解
使用 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 {
}
网友评论