Spring Boot Dersleri – Exception Handling
Spring Boot Dersleri‘ne devam ediyoruz.
Spring Boot uygulamalarımızda Rest API’lerimizde oluşan hataları yakalayıp istemci tarafına anlamlı mesajlar göndermek, sunucu tarafında kayıt altına almak için oluşabilecek hataları ele alma ve hatalara göre istenilen işlemlere ve istisna durumlarına bakacağız.
Bir üye bilgilerini içeren örnek yapacağız.
@XmlRootElement(name = "uye") @XmlAccessorType(XmlAccessType.FIELD) public class Uye extends ResourceSupport implements Serializable { private static final long serialVersionUID = 1L; public Uye(Integer id, String firstName, String lastName, String email) { super(); this.Id = id; this.adi = adi; this.soyadi = soyadi; this.email = email; } public Uye() { } private Integer Id; @NotEmpty(message = "Ad alanı boş geçilemez") private String adi; @NotEmpty(message = "Soyad alanı boş geçilemez") private String soyadi; @NotEmpty(message = "Email alanı boş geçilemez") @Email(message = "Email adresinizi dogrulayınız") private String email; }
Uye classımızın değişkenlerini oluştururken üstüne yazdığımız anotasyonlar ile kurallarımızı oluşturuyoruz.
- @NotEmpty ile boş geçilemez bir alan olduğunu belirtiyoruz ve içerisine hata oluştuğu sırada çıkacak mesajımızı yazıyoruz.
- @Email ile bu değişkenin email validasyonu sağlıyoruz ve hata içeriğini
Üye Rest Controllerimizi oluşturacağız.
@PostMapping(value = "/uyeler") public ResponseEntity<Uye> addUye (@RequestBody Uye uye) { UyeDAO.addUye(uye); return new ResponseEntity<Uye>(uye, HttpStatus.OK); } @GetMapping(value = "/uyeler/{id}") public ResponseEntity<Uye> getUyeById (@PathVariable("id") int id) { Uye uye = UyeDAO.getUyeById(id); if(uye == null) { throw new RecordNotFoundException("Üye bulunamadı: " + id); } return new ResponseEntity<Uye>(uye, HttpStatus.OK); }
Hata mesajlarımızı yönetebileceğimiz entitymizi yapalım. Bu entity bir mesaj ve detayları gösterebilmemizi sağlayacak.
@XmlRootElement(name = "error") public class ErrorResponse { public ErrorResponse(String message, List<String> details) { super(); this.message = message; this.details = details; } private String message; private List<String> details; }
Kayıt bulunamadığı zaman oluşacak olan hatayı ele alıyoruz.
@ResponseStatus(HttpStatus.NOT_FOUND) public class RecordNotFoundException extends RuntimeException { public RecordNotFoundException(String exception) { super(exception); } }
Tüm hatalarımızın ele alacağımız classımızı yazalım. Bu class’da ResponseEntityExceptionHandler’i extend ederek Override ettiğimiz tüm hatalarımızı kontrol edebiliyoruz. Üstte yazdığımız kayıt bulanamadığı zaman oluşacak hatayı RecordNotFoundException‘ı handleUserNotFoundException’a bu class’ı belirterek ilgili değişkenlerimize ekleyebiliyoruz.
@SuppressWarnings({"unchecked","rawtypes"}) @ControllerAdvice public class CustomExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(Exception.class) public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) { List<String> details = new ArrayList<>(); details.add(ex.getLocalizedMessage()); ErrorResponse error = new ErrorResponse("Server Error", details); return new ResponseEntity(error, HttpStatus.INTERNAL_SERVER_ERROR); } @ExceptionHandler(RecordNotFoundException.class) public final ResponseEntity<Object> handleUserNotFoundException(RecordNotFoundException ex, WebRequest request) { List<String> details = new ArrayList<>(); details.add(ex.getLocalizedMessage()); ErrorResponse error = new ErrorResponse("Üye Bulunamadı", details); return new ResponseEntity(error, HttpStatus.NOT_FOUND); } @Override protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { List<String> details = new ArrayList<>(); for(ObjectError error : ex.getBindingResult().getAllErrors()) { details.add(error.getDefaultMessage()); } ErrorResponse error = new ErrorResponse("Validation Failed", details); return new ResponseEntity(error, HttpStatus.BAD_REQUEST); } }
Bu şekilde isteklerden oluşacak hataları ele alıp istenilen işlem ve mesajları gösterebiliriz.
Önceki Ders: SSL İşlemleri , HTTPS Aktif Etmek |
Spring Boot Dersleri |
Sonraki Ders: Initial Data |
Entity katmanına kural koymak tek sorumluluk prensibine aykırı olmaz mı?