package com.example.demo.exception; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import java.util.HashMap; import java.util.Map; /** * Anny's springboot exception class project */ @ControllerAdvice public class MyControllerAdvice { /** * Global catch the exception class, * * Only acts on RequestMapping method, all exceptions are captured information * @Param ex * @return */ @ResponseBody @ExceptionHandler(value = Exception.class) public Map<String,Object> errorHandler(Exception ex){ Map<String,Object> map = new HashMap<>(); map.put("code",-1); map.put("msg",ex.getMessage()); return map; } /** * Custom exception * @Param ex * @return */ @ResponseBody @ExceptionHandler(value = BusinessException.class) public Map<String,Object> errorBusinessHandler(BusinessException ex){ Map<String,Object> map = new HashMap<>(); map.put("code",ex.getCode()); map.put("msg",ex.getMsg()); return map; } }
package com.example.demo.exception; /** * Custom exception class */ public class BusinessException extends RuntimeException { private int code; private String msg; public BusinessException(int code, String msg) { super(); this.code = code; this.msg = msg; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
package com.example.demo.controller; import com.example.demo.exception.BusinessException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/hello") public class HelloController { private static Logger logger = LoggerFactory.getLogger (Hello Controller. class ); @Value("${anny.msg}") private String msg; @RequestMapping ( "/ springBoot" ) public String the Hello () { // abnormalities // int NO = 1/0; // return MSG; // custom exception the throw new new BusinessException (999999999, "what you see" ); } }