Skip to content

Commit 824c567

Browse files
committed
add the exception
1 parent 28df927 commit 824c567

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package taskmanagementsystem.exception;
2+
3+
import lombok.AllArgsConstructor;
4+
import lombok.Getter;
5+
import org.springframework.http.HttpStatus;
6+
7+
@Getter
8+
@AllArgsConstructor
9+
public class ApiException extends RuntimeException{
10+
private HttpStatus status;
11+
private String message;
12+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package taskmanagementsystem.exception;
2+
3+
import org.springframework.http.HttpStatus;
4+
import org.springframework.http.ResponseEntity;
5+
import org.springframework.web.bind.MethodArgumentNotValidException;
6+
import org.springframework.web.bind.annotation.ControllerAdvice;
7+
import org.springframework.web.bind.annotation.ExceptionHandler;
8+
import org.springframework.web.context.request.WebRequest;
9+
10+
import java.time.LocalDateTime;
11+
import java.util.Objects;
12+
13+
@ControllerAdvice
14+
public class GlobalExceptionHandler {
15+
@ExceptionHandler(ResourceNotFoundException.class)
16+
public ResponseEntity<ErrorDetails> handleResourceNotFoundException(ResourceNotFoundException resourceNotFoundException,
17+
WebRequest request){
18+
var errorDetails = new ErrorDetails(
19+
LocalDateTime.now(),
20+
resourceNotFoundException.getMessage(),
21+
request.getDescription(false)
22+
);
23+
return new ResponseEntity<>(errorDetails, HttpStatus.BAD_REQUEST);
24+
}
25+
26+
@ExceptionHandler(ApiException.class)
27+
public ResponseEntity<ErrorDetails> handleTaskApiException(ApiException exception,
28+
WebRequest request){
29+
var errorDetails = new ErrorDetails(
30+
LocalDateTime.now(),
31+
exception.getMessage(),
32+
request.getDescription(false)
33+
);
34+
return new ResponseEntity<>(errorDetails, HttpStatus.BAD_REQUEST);
35+
}
36+
37+
@ExceptionHandler(MethodArgumentNotValidException.class)
38+
public ResponseEntity<ErrorDetails> handleMethodArgumentNotValidException(MethodArgumentNotValidException exception,
39+
WebRequest request){
40+
ErrorDetails errorDetails = new ErrorDetails(
41+
LocalDateTime.now(),
42+
Objects.requireNonNull(exception.getFieldError()).getDefaultMessage(),
43+
request.getDescription(false)
44+
);
45+
46+
return new ResponseEntity<>(errorDetails, HttpStatus.BAD_REQUEST);
47+
}
48+
}

0 commit comments

Comments
 (0)