In SpringBoot, how to handle exceptions?
Before 3.2,
1. The controller level @ExceptionHandler
drawback: it is defined within a controller, and it works only for that controller.
2. The HandlerExceptionResolver:
It offers a uniform exception handler, which is enabled by default Dispatch servlet.
@ExceptionHandler: since Spring 3.1
@ResponseStatus: since Spring 3.0, it is a ResponseStatusExceptionResolver, mapping an Exception to a HttpStatus code.
drawback: 1) it maps an exception to an HTTP status code in the response but without a body massage. 2) one ResponseStatus is able to handle only one Exception.
3. The new one: @ControllerAdvice
Since Spring 3.2 above, it allows scattered handlers resided in one handler, and it allows to customize response body.
Reference:
Error Handling for REST with Spring
Sunday, 20 May 2018
Saturday, 19 May 2018
Spring Data Rest
Spring-Data-Rest builds on top of Spring-Data-Repository. it may automatically analyze underlying data model, and bring out a REST API layer in a hypermedia format. It, implicitly, merged Rest-API within the repository layer. By this way, it removes controller and service layer.
In Spring boot, it is quite simple to initiate a Spring-Data-Rest layer by adding a starter, i.e.
Certainly, it also needs to include following for repository objects, i.e.
In Spring boot, it is quite simple to initiate a Spring-Data-Rest layer by adding a starter, i.e.
org.springframework.boot
spring-boot-starter-data-rest
org.springframework.boot
spring-boot-starter-data-jpa
Wednesday, 9 May 2018
Checked and Unchecked Exception
Java exceptions are categorized into 3 groups.
(1) checked exception: those are verified during compile time.
(2) unchecked exception: those are not verified during compile time.
(3) error (unchecked)
(1): A Checked exception can be predicted by the programmer.
(2): A Unchecked exception is a runtime exception. it may not be predicted as coding it, fx: index out of bound etc.
(3): Errors made by JVM, for instance, run out of memory etc.
An exception extends a Throwable interface. All exceptions are throwables.
(1): extends from Exception extends Throwable; fx: IOException
(2): extends from RuntimeException extends Throwable; for instance: ArithmeticException
(3): extends from Error extends Throwable
(1) must be handled by a developer by try catch finally, or throws to a caller.
(2) not an error; a developer may handle it or not; whatever it will be handled by the system.
(3) Errors come from the system; they cannot be handled.
Rule in inheritance
class A{
doIt(){ }; //overriden method
}
class B extends A{
@override
doIt() throws RuntimeException{ //overriding method
}
}
In general, an overriding method cannot throw an exception more generic than the overridden method. The case above is valid, only because a RuntimeException is an unchecked exception, so the overriding is valid.
(1) checked exception: those are verified during compile time.
(2) unchecked exception: those are not verified during compile time.
(3) error (unchecked)
(1): A Checked exception can be predicted by the programmer.
(2): A Unchecked exception is a runtime exception. it may not be predicted as coding it, fx: index out of bound etc.
(3): Errors made by JVM, for instance, run out of memory etc.
An exception extends a Throwable interface. All exceptions are throwables.
(1): extends from Exception extends Throwable; fx: IOException
(2): extends from RuntimeException extends Throwable; for instance: ArithmeticException
(3): extends from Error extends Throwable
(1) must be handled by a developer by try catch finally, or throws to a caller.
(2) not an error; a developer may handle it or not; whatever it will be handled by the system.
(3) Errors come from the system; they cannot be handled.
Rule in inheritance
class A{
doIt(){ }; //overriden method
}
class B extends A{
@override
doIt() throws RuntimeException{ //overriding method
}
}
In general, an overriding method cannot throw an exception more generic than the overridden method. The case above is valid, only because a RuntimeException is an unchecked exception, so the overriding is valid.
Sunday, 6 May 2018
How to print 1 to 100 without using loop
recursion call works the same as a loop.
/**
*
* @author YNZ
*/
public class PrintOneToNWithoutLoop {
public static void main(String[] args) {
printN(1);
System.out.println("");
}
public static void printN(int n) {
if (n <= 100) {
System.out.print(" " + n);
n++;
printN(n);
}
}
}
Thursday, 3 May 2018
Using Lombok to create Builder Pattern
Applying the builder pattern to a data model is a trivial task. Now it is able to use Lombok annotation to auto-generate it.
import lombok.Getter;
import lombok.Setter;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.time.ZonedDateTime;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.springframework.format.annotation.DateTimeFormat;
/**
*
* @author YNZ
*/
@Entity
@Table(name = "SHARE_ORDER")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@ToString
@EqualsAndHashCode
public class Order implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ORDER_PK")
protected long id;
@OneToOne
@JoinColumn(name = "LISTER_PK_FK", referencedColumnName = "USER_PK")
@NotNull
protected Lister lister;
@OneToOne
@JoinColumn(name = "SEARCHER_PK_FK", referencedColumnName = "USER_PK")
protected Searcher searcher;
@Column(name = "CREATION_TIME")
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
@Builder.Default
protected ZonedDateTime createdDateTime = ZonedDateTime.now();
@Column(name = "ACTIVATED")
protected Boolean activated;
@Column(name = "ORDER_START_TIME")
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
protected ZonedDateTime startTime;
@Column(name = "ORDER_END_TIME")
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
protected ZonedDateTime endTime;
}
Subscribe to:
Posts (Atom)
Can Jackson Deserialize Java Time ZonedDateTime
Yes, but must include JSR310. Thus ZonedDateTime can be deserialized directly from JSON response to POJO field. <dependency> <g...
-
Could not extract response: no suitable HttpMessageConverter found for response type [class dk.enettet.evu.core.model.Address] and content ...
-
First time met this hibernate exception. I think this issue should due to one to one relationship. One driver has one car; one car has on...
-
A large object refers to the entity property that is modified by @Lob. It may be persisted in several records. However, in database manage...