虽然springboot有部分异常处理,但是为了更好的用户体验感,所以我们可以在后台对异常进行统一管理以及自定义,然后前端根据返回的信息以某种方式传达给用户。
这里讲解的是一种方法,还有一种是通过aop切面技术在controller层设置切面从而拦截异常,这里不做介绍,可自行了解。
1、自定义全局异常类:GlobalExceptionHandler
/**
* 全局异常类
* @ControllerAdvice 即可开启全局异常处理,
* 使用该注解表示开启了全局异常的捕获,
* 我们只需在自定义一个方法使用@ExceptionHandler注解
* 然后定义捕获异常的类型即可对这些捕获的异常进行统一的处理。
*
* 也可以自定义异常类,但是需要继承RuntimeException
*/
@Slf4j
@ControllerAdvice//表示在使用@Controller注解的类中如果出现异常就会被该类进行捕捉
public class GlobalExceptionHandler {
@ExceptionHandler(NullPointerException.class)
@ResponseBody
public ResponseEntity<ErrorResponse> handleNullPointerException(NullPointerException e) {
log.info("异常信息:{}",e.getMessage());
ErrorResponse errorResponse = new ErrorResponse("500", e.getMessage());
return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(Exception.class)
@ResponseBody
public ResponseEntity<ErrorResponse> handleException(Exception e) {
log.info("异常信息:{}",e.getMessage());
ErrorResponse errorResponse = new ErrorResponse("500", e.getMessage());
return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(LogInException.class)
@ResponseBody
public ResponseEntity<ErrorResponse> handleLogInException(LogInException e) {
log.info("异常信息:{}",e.getMessage());
ErrorResponse errorResponse = new ErrorResponse(e.getCode(), e.getMessage());
return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
2、异常消息自定义类:
/**
* 异常消息自定义类
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
public class ErrorResponse {
String code;
String message;
}
3、自定义异常类:(要继承RuntimeException)
//登录异常类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class LogInException extends RuntimeException {
String code;
String message;
}
4、测试:
@RestController
@RequestMapping("/books")
public class BooksController {
@GetMapping("/test")
public String test(){
int m=8/0;
return "成功!";
}
@GetMapping("/test2")
public JsonResult<String> test2(@RequestParam String username, @RequestParam String password){
JsonResult<String> jsonResult = new JsonResult<>();
if(username==null||password==null){
throw new LogInException("2","用户名或密码不为空");
}
return jsonResult.success(username,"成功!");
}
}
访问接口:http://127.0.0.1:8080/books/test2
如果只传入一个参数,或者没有参数:
如果按要求传参:
访问接口:http://127.0.0.1:8080/books/test