-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuncheckedexception.html
More file actions
215 lines (182 loc) · 7.9 KB
/
Copy pathuncheckedexception.html
File metadata and controls
215 lines (182 loc) · 7.9 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Spring Boot: Exception Translation Guide</title>
<style>
:root {
--primary-color: #0076A8; /* Professional Blue */
--secondary-color: #86BC25; /* Accent Green */
--bg-color: #f4f7f6;
--text-color: #333;
--code-bg: #282c34;
--code-text: #abb2bf;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
line-height: 1.6;
color: var(--text-color);
background-color: var(--bg-color);
margin: 0;
padding: 20px;
}
.container {
max-width: 900px;
margin: 0 auto;
background: #fff;
padding: 30px;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
border-top: 5px solid var(--primary-color);
}
h1, h2, h3 {
color: var(--primary-color);
}
h1 {
text-align: center;
border-bottom: 2px solid #eee;
padding-bottom: 10px;
margin-bottom: 30px;
}
h2 {
border-left: 4px solid var(--secondary-color);
padding-left: 10px;
margin-top: 40px;
}
p {
margin-bottom: 15px;
}
ul {
margin-bottom: 20px;
}
li {
margin-bottom: 10px;
}
.highlight {
background-color: #eef5f9;
padding: 15px;
border-left: 4px solid var(--primary-color);
border-radius: 4px;
margin: 20px 0;
font-weight: 500;
}
pre {
background-color: var(--code-bg);
color: var(--code-text);
padding: 15px;
border-radius: 6px;
overflow-x: auto;
font-family: 'Courier New', Courier, monospace;
font-size: 14px;
}
code {
font-family: 'Courier New', Courier, monospace;
}
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 20px;
margin-top: 20px;
}
.card {
background: #fff;
border: 1px solid #ddd;
padding: 20px;
border-radius: 6px;
box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}
.card h3 {
margin-top: 0;
color: var(--secondary-color);
}
</style>
</head>
<body>
<div class="container">
<h1>Spring Boot: Exception Translation Review Guide</h1>
<div class="highlight">
<strong>Core Concept:</strong> Spring intentionally adopts a design pattern known as <em>Exception Translation</em> to convert Java's checked exceptions (e.g., <code>SQLException</code>) into unchecked, runtime exceptions (e.g., <code>DataAccessException</code>).
</div>
<h2>Why Does Spring Use Unchecked Exceptions?</h2>
<div class="card-grid">
<div class="card">
<h3>1. Eliminating Boilerplate 🧹</h3>
<p>Prevents "exception pollution". You no longer need to declare <code>throws SQLException</code> on all your service and repository interfaces. It keeps method signatures clean and readable.</p>
</div>
<div class="card">
<h3>2. Vendor Independence 🔌</h3>
<p>Decouples your business logic from specific persistence technologies. Whether an error comes from MySQL, MongoDB, or Redis, Spring wraps it in a unified <code>DataAccessException</code> hierarchy.</p>
</div>
<div class="card">
<h3>3. Non-Recoverable Failures 🛑</h3>
<p>Infrastructure errors (like missing tables or broken DB connections) are fatal at runtime. Since the application cannot realistically recover from them, forcing repetitive <code>try-catch</code> blocks is useless.</p>
</div>
<div class="card">
<h3>4. Global Error Handling 🌐</h3>
<p>Unchecked exceptions bubble up the call stack naturally. This allows you to catch them in one centralized location using <code>@ControllerAdvice</code> and <code>@ExceptionHandler</code>, returning clean JSON responses.</p>
</div>
<div class="card">
<h3>5. @Transactional Alignment 🔄</h3>
<p>By default, Spring's <code>@Transactional</code> only rolls back on <strong>unchecked exceptions</strong> (RuntimeExceptions and Errors). Translating checked database errors into unchecked ones ensures automated and safe transaction rollbacks.</p>
</div>
</div>
<h2>Code Comparison: Traditional vs. Spring</h2>
<h3>Traditional Java (Checked Exception Pollution)</h3>
<pre><code>// The interface is tightly coupled to SQL
public interface UserRepository {
User findById(Long id) throws SQLException;
}
// The caller is forced to handle or declare the exception
public class UserService {
public User getUser(Long id) throws SQLException {
return userRepository.findById(id);
}
}</code></pre>
<h3>Spring Framework (Unchecked Exception Translation)</h3>
<pre><code>// Clean interface, abstract and uncoupled
public interface UserRepository {
User findById(Long id); // Throws DataAccessException implicitly
}
// Clean caller code
@Service
@Transactional
public class UserService {
public User getUser(Long id) {
// No try-catch or throws declaration needed!
return userRepository.findById(id);
}
}</code></pre>
<h2>Practical Example: Custom Unchecked Exceptions & Centralized IAM Handling</h2>
<p>In enterprise-grade microservices and Identity & Access Management (IAM) APIs, custom domain exceptions should inherit from <code>RuntimeException</code> (unchecked). This prevents checked exception propagation across interfaces, letting a global handler safely intercept the failure and return clean REST responses.</p>
<h3>1. Custom Unchecked Domain Exception</h3>
<pre><code>// Custom Unchecked Domain Exception for Authentication
public class InvalidCredentialsException extends RuntimeException {
public InvalidCredentialsException(String msg) {
super(msg);
}
}</code></pre>
<h3>2. Global Controller Exception Handler</h3>
<pre><code>// Spring Boot Global Controller Exception Handler for Identity Management
@RestControllerAdvice
public class IdentityExceptionHandler {
@ExceptionHandler(InvalidCredentialsException.class)
public ResponseEntity<ErrorResponse> handleAuthFailure(InvalidCredentialsException ex) {
ErrorResponse response = new ErrorResponse("AUTH_FAILED", ex.getMessage());
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
}
}
// Simple Error DTO record representation
public record ErrorResponse(String code, String message) {}</code></pre>
<h2>Interview Quick-Fire Questions</h2>
<ul>
<li><strong>Q: What happens if a checked exception is thrown inside a <code>@Transactional</code> method?</strong><br>
<em>A: By default, the transaction will <strong>not</strong> roll back. You must either configure it using <code>rollbackFor = Exception.class</code>, or rely on Spring's exception translation to convert it into an unchecked exception.</em></li>
<li><strong>Q: What is the root class for Spring's database exceptions?</strong><br>
<em>A: <code>org.springframework.dao.DataAccessException</code>, which is a subclass of <code>RuntimeException</code>.</em></li>
<li><strong>Q: How does Spring translate exceptions?</strong><br>
<em>A: Spring uses the <code>PersistenceExceptionTranslator</code> interface, often implemented automatically when using annotations like <code>@Repository</code>.</em></li>
</ul>
</div>
</body>
</html>