-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathGlobalExceptionHandler.java
More file actions
31 lines (26 loc) · 1.34 KB
/
GlobalExceptionHandler.java
File metadata and controls
31 lines (26 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.ironhack.lab_springboot_api.exception;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.MissingRequestHeaderException;
import java.util.HashMap;
import java.util.Map;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, String>> handleValidationExceptions(MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getFieldErrors().forEach(error ->
errors.put(error.getField(), error.getDefaultMessage()));
return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(MissingRequestHeaderException.class)
public ResponseEntity<String> handleMissingHeader(MissingRequestHeaderException ex) {
if (ex.getHeaderName().equals("API-Key")) {
return new ResponseEntity<>("Falta el encabezado API-Key obligatorio", HttpStatus.UNAUTHORIZED);
}
return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST);
}
}