Giriş
Şu satırı dahil ederiz
import org.springframework.web.server.ResponseStatusException;
Bu sınıfın iki kullanım yöntemi var
1. Servis kodundan fırlatılır ve istemciye kadar gitmesine izin verilir
2. Servis kodundan fırlatılır ve @ExceptionHandler(ResponseStatusException.class) ile yakalanarak bir exception sonucu nesnesine çevrilir.
Ancak bu iki yöntem yerine şu yöntem tercih edilebilir. Açıklaması şöyle
This exception can even be used at the service level and that approach can help you in terms of the number of exceptions you are creating. But as you can probably guess by now it is not a good solution for unified exception handling compared to ControllerAdvice or HandlerExceptionResolver.
Örnek
Şöyle yaparız
@RestController@RequestMapping("/api/v1/")public class StudentRestController {@AutowiredStudentService studentService;@GetMapping("student/{id}")public ResponseEntity<Student> getUser(@PathVariable(name = "id", required = false) Long id ) {Student student;try {student = studentService.findStudentById(null);} catch (InvalidIdException e) {throw new ResponseStatusException(HttpStatus.BAD_REQUEST,e.getMessage(), e);} catch (ServiceDownTimeException e) {throw new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE,e.getMessage(), e);}return ResponseEntity.status(HttpStatus.OK).body(student);}}
HTTP sonucu şöyle
{ "timestamp": "2022-05-20T19:17:54.442+00:00", "status": 503, "error": "Service Unavailable", "message": "1-2 AM is service downtime!", "path": "/api/v1/student/1" }
Örnek - Kalıtım
Şöyle yaparız
public class NoSuchElementFoundException extends ResponseStatusException {public NoSuchElementFoundException(String message){super(HttpStatus.NOT_FOUND, message);}@Overridepublic HttpHeaders getResponseHeaders() {// return response headers}}
Spring 3 ile ResponseStatusException -> getStatus() metodu yerine getStatusCode() metodu geldi
Örnek
Şöyle yaparız
@ExceptionHandler(ResponseStatusException.class) public ResponseEntity<ErrorResponse> handleNotFound(ResponseStatusException exception) { final ErrorResponse errorResponse = new ErrorResponse(); // errorResponse.setHttpStatus(exception.getStatus().value()); errorResponse.setHttpStatus(exception.getStatusCode().value()); errorResponse.setException(exception.getClass().getSimpleName()); errorResponse.setMessage(exception.getMessage()); // return new ResponseEntity<>(errorResponse, exception.getStatus()); return new ResponseEntity<>(errorResponse, exception.getStatusCode()); }
Hiç yorum yok:
Yorum Gönder