Spring boot - Exception handling

less than 1 minute read

SpringBoot allow to define the exception handler inside of Controller. The following code shows an example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Controller
@ResponseBody
public class RestController {

  @ExceptionHandler
  @ResponseStatus(HttpStatus.BAD_REQUEST)
  public ResponseEntity<?> exceptionHandler(Exception e) {
    return ResponseEntity.badRequest().build()
  }

  @GetMapping("/hello/{name}")
  public Mono<Item> hello(@PathVariable String name) {
    return Mono.just(new Item(name));
  }

  @GetMapping(value = "/stream/{name}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
  public Flux<Item> Flux.fromStream(stream.generate(() -> new Item(name)))
                          .take(10)
                          .delayElements(Duration.ofSeconds(1));
}

record Item(String name) {}

Categories:

Updated: