Post

Spring) Spring Boot ExceptionHandler / Optional

Spring) Spring Boot ExceptionHandler / Optional

This post was migrated from Tistory. You can find the original here.

ExceptionHandler

1
2
3
4
5
6
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<ExceptionResponseDto> postPatchHandle(IllegalArgumentException e){
        HttpStatus httpStatus = HttpStatus.BAD_REQUEST;
        ExceptionResponseDto response = new ExceptionResponseDto(httpStatus, e.getMessage());
        return new ResponseEntity<>(response, httpStatus);
    }

This runs when the exception specified in the handler is thrown in the controller that the @ExceptionHandler belongs to.
ResponseEntity lets you set the response’s headers, body, and status.

If you want to handle exceptions globally across controllers, look into keywords like @ControllerAdvice.

Optional

1
2
3
4
5
6
public class PostUpdateDto extends PostUserDto {
    private String username;
    private String password;
    private Optional<String> title;
    private Optional<String> contents;
}
1
2
3
4
public void update(PostUpdateDto requestDto){
    if(Optional.ofNullable(requestDto.getTitle()).isPresent()) setTitle(requestDto.getTitle().get());
    if(Optional.ofNullable(requestDto.getContents()).isPresent()) setContents(requestDto.getContents().get());
}
1
2
3
4
5
6
7
8
9
10
private static final Optional<?> EMPTY = new Optional<>(null);

public static <T> Optional<T> ofNullable(T value) {
    return value == null ? (Optional<T>) EMPTY
                             : new Optional<>(value);
}

public boolean isPresent() {
    return value != null;
}

Optional.ofNullable wraps the value in an Optional, and isPresent returns a boolean.

why

What about Optional chaining in Java?
Isn’t there something like TypeScript’s Partial<T>?
How does Lombok interact with inheritance?

This post is licensed under CC BY-NC 4.0 by the author.