├── .gitignore ├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── LICENSE ├── README.md ├── mvnw ├── mvnw.cmd ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── example │ │ └── springbootexceptionhandling │ │ ├── DbInit.java │ │ ├── EntityNotFoundException.java │ │ ├── LowerCaseClassNameResolver.java │ │ ├── RestExceptionHandler.java │ │ ├── SpringBootExceptionHandlingApplication.java │ │ ├── apierror │ │ ├── ApiError.java │ │ ├── ApiSubError.java │ │ └── ApiValidationError.java │ │ └── bird │ │ ├── Bird.java │ │ ├── BirdCollection.java │ │ ├── BirdController.java │ │ ├── BirdObjectMother.java │ │ ├── BirdRepository.java │ │ └── BirdService.java └── resources │ ├── application-no-handler.properties │ └── application.properties └── test └── java └── com └── example └── springbootexceptionhandling └── bird └── BirdRepositoryTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | 18 | ### NetBeans ### 19 | nbproject/private/ 20 | build/ 21 | nbbuild/ 22 | dist/ 23 | nbdist/ 24 | .nb-gradle/ -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brunocleite/spring-boot-exception-handling/81f44e6502a1812107dc54eba1f311221e298675/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.0/apache-maven-3.5.0-bin.zip 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Bruno Leite 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Spring Boot Exception Handling 2 | Final source code accompanying the article on the Toptal Blog. 3 | 4 | https://www.toptal.com/java/spring-boot-rest-api-error-handling 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Migwn, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.example 7 | spring-boot-exception-handling 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | spring-boot-exception-handling 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 1.5.4.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-data-jpa 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-web 35 | 36 | 37 | 38 | org.springframework.boot 39 | spring-boot-starter-test 40 | test 41 | 42 | 43 | 44 | com.fasterxml.jackson.datatype 45 | jackson-datatype-jsr310 46 | 47 | 48 | 49 | 50 | org.projectlombok 51 | lombok 52 | provided 53 | 54 | 55 | 56 | 57 | com.h2database 58 | h2 59 | 2.1.210 60 | 61 | 62 | 63 | 64 | org.apache.commons 65 | commons-lang3 66 | 3.5 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | org.springframework.boot 75 | spring-boot-maven-plugin 76 | 77 | 78 | 79 | 80 | 81 | 82 | -------------------------------------------------------------------------------- /src/main/java/com/example/springbootexceptionhandling/DbInit.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootexceptionhandling; 2 | 3 | import com.example.springbootexceptionhandling.bird.BirdObjectMother; 4 | import com.example.springbootexceptionhandling.bird.BirdRepository; 5 | import lombok.AllArgsConstructor; 6 | import lombok.extern.slf4j.Slf4j; 7 | import org.springframework.boot.ApplicationArguments; 8 | import org.springframework.boot.ApplicationRunner; 9 | import org.springframework.stereotype.Component; 10 | 11 | @Component 12 | @Slf4j 13 | @AllArgsConstructor 14 | public class DbInit implements ApplicationRunner { 15 | 16 | private BirdRepository birdRepository; 17 | 18 | public void run(ApplicationArguments args) { 19 | log.info("Populating database with sample data..."); 20 | birdRepository.save(BirdObjectMother.createCanary()); 21 | } 22 | } -------------------------------------------------------------------------------- /src/main/java/com/example/springbootexceptionhandling/EntityNotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootexceptionhandling; 2 | 3 | import org.apache.commons.lang3.StringUtils; 4 | 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | import java.util.stream.IntStream; 8 | 9 | public class EntityNotFoundException extends RuntimeException { 10 | 11 | public EntityNotFoundException(Class clazz, String... searchParamsMap) { 12 | super(EntityNotFoundException.generateMessage(clazz.getSimpleName(), toMap(String.class, String.class, searchParamsMap))); 13 | } 14 | 15 | private static String generateMessage(String entity, Map searchParams) { 16 | return StringUtils.capitalize(entity) + 17 | " was not found for parameters " + 18 | searchParams; 19 | } 20 | 21 | private static Map toMap( 22 | Class keyType, Class valueType, Object... entries) { 23 | if (entries.length % 2 == 1) 24 | throw new IllegalArgumentException("Invalid entries"); 25 | return IntStream.range(0, entries.length / 2).map(i -> i * 2) 26 | .collect(HashMap::new, 27 | (m, i) -> m.put(keyType.cast(entries[i]), valueType.cast(entries[i + 1])), 28 | Map::putAll); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/example/springbootexceptionhandling/LowerCaseClassNameResolver.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootexceptionhandling; 2 | 3 | import com.fasterxml.jackson.annotation.JsonTypeInfo; 4 | import com.fasterxml.jackson.databind.jsontype.impl.TypeIdResolverBase; 5 | 6 | public class LowerCaseClassNameResolver extends TypeIdResolverBase { 7 | 8 | @Override 9 | public String idFromValue(Object value) { 10 | return value.getClass().getSimpleName().toLowerCase(); 11 | } 12 | 13 | @Override 14 | public String idFromValueAndType(Object value, Class suggestedType) { 15 | return idFromValue(value); 16 | } 17 | 18 | @Override 19 | public JsonTypeInfo.Id getMechanism() { 20 | return JsonTypeInfo.Id.CUSTOM; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/example/springbootexceptionhandling/RestExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootexceptionhandling; 2 | 3 | import com.example.springbootexceptionhandling.apierror.ApiError; 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.hibernate.exception.ConstraintViolationException; 6 | import org.springframework.core.Ordered; 7 | import org.springframework.core.annotation.Order; 8 | import org.springframework.dao.DataIntegrityViolationException; 9 | import org.springframework.http.HttpHeaders; 10 | import org.springframework.http.HttpStatus; 11 | import org.springframework.http.ResponseEntity; 12 | import org.springframework.http.converter.HttpMessageNotReadableException; 13 | import org.springframework.http.converter.HttpMessageNotWritableException; 14 | import org.springframework.web.HttpMediaTypeNotSupportedException; 15 | import org.springframework.web.bind.MethodArgumentNotValidException; 16 | import org.springframework.web.bind.MissingServletRequestParameterException; 17 | import org.springframework.web.bind.annotation.ControllerAdvice; 18 | import org.springframework.web.bind.annotation.ExceptionHandler; 19 | import org.springframework.web.context.request.ServletWebRequest; 20 | import org.springframework.web.context.request.WebRequest; 21 | import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; 22 | import org.springframework.web.servlet.NoHandlerFoundException; 23 | import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; 24 | 25 | import static org.springframework.http.HttpStatus.BAD_REQUEST; 26 | import static org.springframework.http.HttpStatus.NOT_FOUND; 27 | 28 | @Order(Ordered.HIGHEST_PRECEDENCE) 29 | @ControllerAdvice 30 | @Slf4j 31 | public class RestExceptionHandler extends ResponseEntityExceptionHandler { 32 | 33 | /** 34 | * Handle MissingServletRequestParameterException. Triggered when a 'required' request parameter is missing. 35 | * 36 | * @param ex MissingServletRequestParameterException 37 | * @param headers HttpHeaders 38 | * @param status HttpStatus 39 | * @param request WebRequest 40 | * @return the ApiError object 41 | */ 42 | @Override 43 | protected ResponseEntity handleMissingServletRequestParameter( 44 | MissingServletRequestParameterException ex, HttpHeaders headers, 45 | HttpStatus status, WebRequest request) { 46 | String error = ex.getParameterName() + " parameter is missing"; 47 | return buildResponseEntity(new ApiError(BAD_REQUEST, error, ex)); 48 | } 49 | 50 | 51 | /** 52 | * Handle HttpMediaTypeNotSupportedException. This one triggers when JSON is invalid as well. 53 | * 54 | * @param ex HttpMediaTypeNotSupportedException 55 | * @param headers HttpHeaders 56 | * @param status HttpStatus 57 | * @param request WebRequest 58 | * @return the ApiError object 59 | */ 60 | @Override 61 | protected ResponseEntity handleHttpMediaTypeNotSupported( 62 | HttpMediaTypeNotSupportedException ex, 63 | HttpHeaders headers, 64 | HttpStatus status, 65 | WebRequest request) { 66 | StringBuilder builder = new StringBuilder(); 67 | builder.append(ex.getContentType()); 68 | builder.append(" media type is not supported. Supported media types are "); 69 | ex.getSupportedMediaTypes().forEach(t -> builder.append(t).append(", ")); 70 | return buildResponseEntity(new ApiError(HttpStatus.UNSUPPORTED_MEDIA_TYPE, builder.substring(0, builder.length() - 2), ex)); 71 | } 72 | 73 | /** 74 | * Handle MethodArgumentNotValidException. Triggered when an object fails @Valid validation. 75 | * 76 | * @param ex the MethodArgumentNotValidException that is thrown when @Valid validation fails 77 | * @param headers HttpHeaders 78 | * @param status HttpStatus 79 | * @param request WebRequest 80 | * @return the ApiError object 81 | */ 82 | @Override 83 | protected ResponseEntity handleMethodArgumentNotValid( 84 | MethodArgumentNotValidException ex, 85 | HttpHeaders headers, 86 | HttpStatus status, 87 | WebRequest request) { 88 | ApiError apiError = new ApiError(BAD_REQUEST); 89 | apiError.setMessage("Validation error"); 90 | apiError.addValidationErrors(ex.getBindingResult().getFieldErrors()); 91 | apiError.addValidationError(ex.getBindingResult().getGlobalErrors()); 92 | return buildResponseEntity(apiError); 93 | } 94 | 95 | /** 96 | * Handles javax.validation.ConstraintViolationException. Thrown when @Validated fails. 97 | * 98 | * @param ex the ConstraintViolationException 99 | * @return the ApiError object 100 | */ 101 | @ExceptionHandler(javax.validation.ConstraintViolationException.class) 102 | protected ResponseEntity handleConstraintViolation( 103 | javax.validation.ConstraintViolationException ex) { 104 | ApiError apiError = new ApiError(BAD_REQUEST); 105 | apiError.setMessage("Validation error"); 106 | apiError.addValidationErrors(ex.getConstraintViolations()); 107 | return buildResponseEntity(apiError); 108 | } 109 | 110 | /** 111 | * Handles EntityNotFoundException. Created to encapsulate errors with more detail than javax.persistence.EntityNotFoundException. 112 | * 113 | * @param ex the EntityNotFoundException 114 | * @return the ApiError object 115 | */ 116 | @ExceptionHandler(EntityNotFoundException.class) 117 | protected ResponseEntity handleEntityNotFound( 118 | EntityNotFoundException ex) { 119 | ApiError apiError = new ApiError(NOT_FOUND); 120 | apiError.setMessage(ex.getMessage()); 121 | return buildResponseEntity(apiError); 122 | } 123 | 124 | /** 125 | * Handle HttpMessageNotReadableException. Happens when request JSON is malformed. 126 | * 127 | * @param ex HttpMessageNotReadableException 128 | * @param headers HttpHeaders 129 | * @param status HttpStatus 130 | * @param request WebRequest 131 | * @return the ApiError object 132 | */ 133 | @Override 134 | protected ResponseEntity handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { 135 | ServletWebRequest servletWebRequest = (ServletWebRequest) request; 136 | log.info("{} to {}", servletWebRequest.getHttpMethod(), servletWebRequest.getRequest().getServletPath()); 137 | String error = "Malformed JSON request"; 138 | return buildResponseEntity(new ApiError(HttpStatus.BAD_REQUEST, error, ex)); 139 | } 140 | 141 | /** 142 | * Handle HttpMessageNotWritableException. 143 | * 144 | * @param ex HttpMessageNotWritableException 145 | * @param headers HttpHeaders 146 | * @param status HttpStatus 147 | * @param request WebRequest 148 | * @return the ApiError object 149 | */ 150 | @Override 151 | protected ResponseEntity handleHttpMessageNotWritable(HttpMessageNotWritableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { 152 | String error = "Error writing JSON output"; 153 | return buildResponseEntity(new ApiError(HttpStatus.INTERNAL_SERVER_ERROR, error, ex)); 154 | } 155 | 156 | /** 157 | * Handle NoHandlerFoundException. 158 | * 159 | * @param ex 160 | * @param headers 161 | * @param status 162 | * @param request 163 | * @return 164 | */ 165 | @Override 166 | protected ResponseEntity handleNoHandlerFoundException( 167 | NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { 168 | ApiError apiError = new ApiError(BAD_REQUEST); 169 | apiError.setMessage(String.format("Could not find the %s method for URL %s", ex.getHttpMethod(), ex.getRequestURL())); 170 | apiError.setDebugMessage(ex.getMessage()); 171 | return buildResponseEntity(apiError); 172 | } 173 | 174 | /** 175 | * Handle javax.persistence.EntityNotFoundException 176 | */ 177 | @ExceptionHandler(javax.persistence.EntityNotFoundException.class) 178 | protected ResponseEntity handleEntityNotFound(javax.persistence.EntityNotFoundException ex) { 179 | return buildResponseEntity(new ApiError(HttpStatus.NOT_FOUND, ex)); 180 | } 181 | 182 | /** 183 | * Handle DataIntegrityViolationException, inspects the cause for different DB causes. 184 | * 185 | * @param ex the DataIntegrityViolationException 186 | * @return the ApiError object 187 | */ 188 | @ExceptionHandler(DataIntegrityViolationException.class) 189 | protected ResponseEntity handleDataIntegrityViolation(DataIntegrityViolationException ex, 190 | WebRequest request) { 191 | if (ex.getCause() instanceof ConstraintViolationException) { 192 | return buildResponseEntity(new ApiError(HttpStatus.CONFLICT, "Database error", ex.getCause())); 193 | } 194 | return buildResponseEntity(new ApiError(HttpStatus.INTERNAL_SERVER_ERROR, ex)); 195 | } 196 | 197 | /** 198 | * Handle Exception, handle generic Exception.class 199 | * 200 | * @param ex the Exception 201 | * @return the ApiError object 202 | */ 203 | @ExceptionHandler(MethodArgumentTypeMismatchException.class) 204 | protected ResponseEntity handleMethodArgumentTypeMismatch(MethodArgumentTypeMismatchException ex, 205 | WebRequest request) { 206 | ApiError apiError = new ApiError(BAD_REQUEST); 207 | apiError.setMessage(String.format("The parameter '%s' of value '%s' could not be converted to type '%s'", ex.getName(), ex.getValue(), ex.getRequiredType().getSimpleName())); 208 | apiError.setDebugMessage(ex.getMessage()); 209 | return buildResponseEntity(apiError); 210 | } 211 | 212 | 213 | private ResponseEntity buildResponseEntity(ApiError apiError) { 214 | return new ResponseEntity<>(apiError, apiError.getStatus()); 215 | } 216 | 217 | } 218 | -------------------------------------------------------------------------------- /src/main/java/com/example/springbootexceptionhandling/SpringBootExceptionHandlingApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootexceptionhandling; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SpringBootExceptionHandlingApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SpringBootExceptionHandlingApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/example/springbootexceptionhandling/apierror/ApiError.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootexceptionhandling.apierror; 2 | 3 | import com.example.springbootexceptionhandling.LowerCaseClassNameResolver; 4 | import com.fasterxml.jackson.annotation.JsonFormat; 5 | import com.fasterxml.jackson.annotation.JsonTypeInfo; 6 | import com.fasterxml.jackson.databind.annotation.JsonTypeIdResolver; 7 | import lombok.Data; 8 | import org.hibernate.validator.internal.engine.path.PathImpl; 9 | import org.springframework.http.HttpStatus; 10 | import org.springframework.validation.FieldError; 11 | import org.springframework.validation.ObjectError; 12 | 13 | import javax.validation.ConstraintViolation; 14 | import java.time.LocalDateTime; 15 | import java.util.ArrayList; 16 | import java.util.List; 17 | import java.util.Set; 18 | 19 | @Data 20 | @JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.CUSTOM, property = "error", visible = true) 21 | @JsonTypeIdResolver(LowerCaseClassNameResolver.class) 22 | public 23 | class ApiError { 24 | 25 | private HttpStatus status; 26 | @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss") 27 | private LocalDateTime timestamp; 28 | private String message; 29 | private String debugMessage; 30 | private List subErrors; 31 | 32 | private ApiError() { 33 | timestamp = LocalDateTime.now(); 34 | } 35 | 36 | public ApiError(HttpStatus status) { 37 | this(); 38 | this.status = status; 39 | } 40 | 41 | public ApiError(HttpStatus status, Throwable ex) { 42 | this(); 43 | this.status = status; 44 | this.message = "Unexpected error"; 45 | this.debugMessage = ex.getLocalizedMessage(); 46 | } 47 | 48 | public ApiError(HttpStatus status, String message, Throwable ex) { 49 | this(); 50 | this.status = status; 51 | this.message = message; 52 | this.debugMessage = ex.getLocalizedMessage(); 53 | } 54 | 55 | private void addSubError(ApiSubError subError) { 56 | if (subErrors == null) { 57 | subErrors = new ArrayList<>(); 58 | } 59 | subErrors.add(subError); 60 | } 61 | 62 | private void addValidationError(String object, String field, Object rejectedValue, String message) { 63 | addSubError(new ApiValidationError(object, field, rejectedValue, message)); 64 | } 65 | 66 | private void addValidationError(String object, String message) { 67 | addSubError(new ApiValidationError(object, message)); 68 | } 69 | 70 | private void addValidationError(FieldError fieldError) { 71 | this.addValidationError( 72 | fieldError.getObjectName(), 73 | fieldError.getField(), 74 | fieldError.getRejectedValue(), 75 | fieldError.getDefaultMessage()); 76 | } 77 | 78 | public void addValidationErrors(List fieldErrors) { 79 | fieldErrors.forEach(this::addValidationError); 80 | } 81 | 82 | private void addValidationError(ObjectError objectError) { 83 | this.addValidationError( 84 | objectError.getObjectName(), 85 | objectError.getDefaultMessage()); 86 | } 87 | 88 | public void addValidationError(List globalErrors) { 89 | globalErrors.forEach(this::addValidationError); 90 | } 91 | 92 | /** 93 | * Utility method for adding error of ConstraintViolation. Usually when a @Validated validation fails. 94 | * 95 | * @param cv the ConstraintViolation 96 | */ 97 | private void addValidationError(ConstraintViolation cv) { 98 | this.addValidationError( 99 | cv.getRootBeanClass().getSimpleName(), 100 | ((PathImpl) cv.getPropertyPath()).getLeafNode().asString(), 101 | cv.getInvalidValue(), 102 | cv.getMessage()); 103 | } 104 | 105 | public void addValidationErrors(Set> constraintViolations) { 106 | constraintViolations.forEach(this::addValidationError); 107 | } 108 | 109 | 110 | } 111 | 112 | -------------------------------------------------------------------------------- /src/main/java/com/example/springbootexceptionhandling/apierror/ApiSubError.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootexceptionhandling.apierror; 2 | 3 | public abstract class ApiSubError { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/example/springbootexceptionhandling/apierror/ApiValidationError.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootexceptionhandling.apierror; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | import lombok.EqualsAndHashCode; 6 | 7 | @Data 8 | @EqualsAndHashCode(callSuper = false) 9 | @AllArgsConstructor 10 | public class ApiValidationError extends ApiSubError { 11 | private String object; 12 | private String field; 13 | private Object rejectedValue; 14 | private String message; 15 | 16 | ApiValidationError(String object, String message) { 17 | this.object = object; 18 | this.message = message; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/example/springbootexceptionhandling/bird/Bird.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootexceptionhandling.bird; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Builder; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | import javax.persistence.*; 9 | import javax.validation.constraints.Max; 10 | import javax.validation.constraints.NotNull; 11 | 12 | @Data 13 | @Builder 14 | @NoArgsConstructor 15 | @AllArgsConstructor 16 | 17 | @Entity 18 | public class Bird { 19 | 20 | @Id 21 | @GeneratedValue(strategy = GenerationType.AUTO) 22 | @Column(name = "ID") 23 | private Long id; 24 | 25 | @Column(name = "SCIENTIFIC_NAME") 26 | @NotNull 27 | private String scientificName; 28 | 29 | @Column(name = "SPECIE") 30 | @NotNull 31 | private String specie; 32 | 33 | @Column(name = "MASS") 34 | @NotNull 35 | @Max(104000) 36 | private Double mass; 37 | 38 | @Column(name = "LENGTH") 39 | @NotNull 40 | @Max(210) 41 | private Integer length; 42 | 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/example/springbootexceptionhandling/bird/BirdCollection.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootexceptionhandling.bird; 2 | 3 | import javax.validation.constraints.NotNull; 4 | import javax.validation.constraints.Size; 5 | import java.util.List; 6 | 7 | public class BirdCollection { 8 | 9 | @NotNull 10 | @Size(min = 2) 11 | private List birdsIds; 12 | 13 | public List getBirdsIds() { 14 | return birdsIds; 15 | } 16 | 17 | public void setBirdsIds(List birds) { 18 | this.birdsIds = birds; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/example/springbootexceptionhandling/bird/BirdController.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootexceptionhandling.bird; 2 | 3 | import com.example.springbootexceptionhandling.EntityNotFoundException; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.web.bind.annotation.*; 6 | 7 | import javax.validation.Valid; 8 | import java.util.List; 9 | 10 | @RestController 11 | @RequestMapping("/birds") 12 | public class BirdController { 13 | 14 | @Autowired 15 | private BirdService birdService; 16 | 17 | @GetMapping(value = "/{birdId}") 18 | public Bird getBird(@PathVariable("birdId") Long birdId) throws EntityNotFoundException { 19 | return birdService.getBird(birdId); 20 | } 21 | 22 | @GetMapping(value = "/collection") 23 | public List getBirdValid(@RequestBody BirdCollection birdCollection) throws EntityNotFoundException { 24 | return birdService.getBirdCollection(birdCollection); 25 | } 26 | 27 | @GetMapping(value = "/params") 28 | public Bird getBirdRequestParam(@RequestParam("birdId") Long birdId) throws EntityNotFoundException { 29 | return birdService.getBird(birdId); 30 | } 31 | 32 | @GetMapping(value = "/noexception/{birdId}") 33 | public Bird getBirdNoException(@PathVariable("birdId") Long birdId) throws EntityNotFoundException { 34 | return birdService.getBirdNoException(birdId); 35 | } 36 | 37 | 38 | @PostMapping 39 | public Bird createBird(@RequestBody @Valid Bird bird) { 40 | return birdService.createBird(bird); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/example/springbootexceptionhandling/bird/BirdObjectMother.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootexceptionhandling.bird; 2 | 3 | public abstract class BirdObjectMother { 4 | 5 | public static Bird createCanary() { 6 | return Bird.builder() 7 | .scientificName("Atlantic canary") 8 | .specie("serinus canaria") 9 | .length(11) 10 | .mass(10d) 11 | .build(); 12 | 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/example/springbootexceptionhandling/bird/BirdRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootexceptionhandling.bird; 2 | 3 | import org.springframework.data.repository.CrudRepository; 4 | 5 | public interface BirdRepository extends CrudRepository { 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/com/example/springbootexceptionhandling/bird/BirdService.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootexceptionhandling.bird; 2 | 3 | import com.example.springbootexceptionhandling.EntityNotFoundException; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.stereotype.Service; 6 | 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | @Service 11 | public class BirdService { 12 | 13 | @Autowired 14 | private BirdRepository birdRepository; 15 | 16 | public Bird getBirdNoException(Long birdId) { 17 | return birdRepository.findOne(birdId); 18 | } 19 | 20 | public Bird getBird(Long birdId) { 21 | Bird bird = birdRepository.findOne(birdId); 22 | if (bird == null) { 23 | throw new EntityNotFoundException(Bird.class, "id", birdId.toString()); 24 | } 25 | return bird; 26 | } 27 | 28 | public Bird createBird(Bird bird) { 29 | return birdRepository.save(bird); 30 | } 31 | 32 | public List getBirdCollection(BirdCollection birdCollection) { 33 | List birds = new ArrayList<>(); 34 | 35 | for (Long birdId : birdCollection.getBirdsIds()) { 36 | Bird bird = birdRepository.findOne(birdId); 37 | if (bird == null) { 38 | throw new EntityNotFoundException(Bird.class, "id", birdId.toString()); 39 | } 40 | birds.add(bird); 41 | } 42 | return birds; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/resources/application-no-handler.properties: -------------------------------------------------------------------------------- 1 | spring.jackson.default-property-inclusion=non_null 2 | spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration 3 | spring.mvc.throw-exception-if-no-handler-found=true 4 | spring.resources.add-mappings=false -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.jackson.default-property-inclusion=NON_NULL 2 | -------------------------------------------------------------------------------- /src/test/java/com/example/springbootexceptionhandling/bird/BirdRepositoryTest.java: -------------------------------------------------------------------------------- 1 | package com.example.springbootexceptionhandling.bird; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; 7 | import org.springframework.test.context.junit4.SpringRunner; 8 | 9 | import static com.example.springbootexceptionhandling.bird.BirdObjectMother.createCanary; 10 | 11 | @RunWith(SpringRunner.class) 12 | @DataJpaTest 13 | public class BirdRepositoryTest { 14 | 15 | @Autowired 16 | private BirdRepository birdRepository; 17 | 18 | @Test 19 | public void canSaveBird() { 20 | birdRepository.save(createCanary()); 21 | } 22 | 23 | } --------------------------------------------------------------------------------